Rails:为需要来自其自己类的成员的信息的类创建一个方法?
我想知道是否可以执行如下操作:
假设我有一个 Rails 模型 Foo
,带有数据库属性 value
。 Foo
属于 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
这样的事情可以完成吗?如果可以,如何完成?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要您确保在
average
方法主体中调用self
上的方法而不是Foo
上的方法,您所拥有的就可以按原样工作。当调用Foo
作用域上的方法时,该方法主体中的self
将被分配给作用域对象,而不是Foo
。这是一个更具体的例子:让我们看看当我们创建一些俱乐部和人员时会发生什么:
What you have will work as is, as long as you make sure to call methods on
self
instead ofFoo
in the body of theaverage
method. When calling methods on a scope ofFoo
,self
in 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: