ruby on rails - Passing value from child class to parent -
a package made of expense, revenue, , balance based on sales made of amount. how add each @sale.amount
@package.revenue
?
model package.rb:
class package < activerecord::base has_many :sales end
model sale.rb:
class sale < activerecord::base belongs_to :package end
routes.rb:
rails.application.routes.draw resources :packages resources :sales end end end
activerecord has handy sum
method calculating sum of values in column:
class package < activerecord::base has_many :sales def revenue sales.sum(:amount) end end
note while looks similar sales.map(&:amount).sum
performance vastly better because activerecord let database calculation , retrieve single value (the final sum) database, whereas other method fetch every associated record database (of there may many thousands), instantiate sale object each one, amount
each sale object , calculate sum.
Comments
Post a Comment