I was wondering if it’s possible to do something like follows:
Let’s say I have a Rails model, Foo, with a database attribute value. Foo belongs_to Bar, Bar has_many Foos.
In my model, I’d like to do something like:
class Foo < ActiveRecord::Base
belongs_to :bar
def self.average
# return the value of all foos here
end
end
Ideally I’d like to have this method return a value that matched the scope from which it was called, so that:
Foo.average # would return the average value of all foos
@bar = Bar.find(1)
@bar.foos.average # would return the average of all foos where bar_id == 1
Can such a thing be done, and if so, how? Thanks!
What you have will work as is, as long as you make sure to call methods on
selfinstead ofFooin the body of theaveragemethod. When calling methods on a scope ofFoo,selfin the body of that method will be assigned to the scope object rather thanFoo. Here’s a slightly more concrete example:Let’s see what happens when we create some clubs and people: