0
我想知道是否有可能做這樣的事情如下:Rails:爲需要來自其類的成員的信息的類創建方法?
比方說,我有一個Rails的模式,Foo
,與數據庫屬性value
。 Foo
belongs_to Bar
,Bar
has_many Foos
。
在我的模型,我想這樣做:
class Foo < ActiveRecord::Base
belongs_to :bar
def self.average
# return the value of all foos here
end
end
理想我想有這個方法返回匹配的從它被稱爲範圍值,使:
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
可以做這樣的事情,如果是這樣,如何?謝謝!
啊哈!我不知道'count',我在想我需要做一些像'self.each do {#stuff}`這顯然不起作用的東西。謝謝,這非常有幫助! – Andrew 2011-01-19 02:14:26