Reputation: 6815
My entry
model has many counters:
class Entry < ActiveRecord::Base
has_many :counters
end
Every counter
has a number
, and the total
represents the sum of the numbers
:
class Counter < ActiveRecord::Base
scope :total, sum(:number)
end
I need to get the sum of all the numbers of the counters which belong to a specific entry.
In SQL it would be:
SELECT SUM(`number`) AS `total` FROM `counters` WHERE `entry_id` = entry.id
I tried:
entry.counters.total
But it returns:
NoMethodError: undefined method `default_scoped?' for 0:Fixnum
Is there any "Rails way" to do this nicely with ActiveRecord associations and scopes?
Upvotes: 0
Views: 1336
Reputation: 84114
In your example the call to sum
happens straightaway, ie your code is equivalent to
scope :total, 0
(assuming that the sum is 0 at the moment that your class is 0), which isn't valid
Fundamentally scopes are about scoping a result set : adding conditions, order, limit or options such as joins, but with the constant that the result is a collection of active record objects.
What you want to do is best expressed as a class method:
def self.total
sum(:number)
end
You can still chain this onto a scope, for example
some_entry.counters.total
Upvotes: 1