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?
In your example the call to
sumhappens straightaway, ie your code is equivalent to(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:
You can still chain this onto a scope, for example