Reputation: 237
i have two models Vote and Option,each with column "total" and "quantity". (Vote has_many:options)
I want to implement like this initially:
Option.quantities.each{ |quantity| total+=quantity}
Vote.total=total
how to implement that??
Upvotes: 0
Views: 56
Reputation: 4041
Are you asking for an alternate implementation? Or for something else? You can do the same thing with Enumerable::inject
, for example:
class Vote < ActiveRecord::Base
has_many :options
def calculate_total
total = self.options.inject(0) { |sum, vote| sum += vote.quantity }
save!
end
end
In this way, the Vote total is calculated and saved every time calculate_total
is called.
Upvotes: 1