如何加入具有 Active Record 中范围的 has_many 关联?
这是我的关联和范围设置:
has_many :owned_products
has_many :owned_lessons, :through => :owned_products, :source => :lesson, :conditions => "owned_products.product_type = 'Lesson'"
scope :active_purchase_scope, lambda {
where('owned_products.created_at' => (Date.today - CONFIG['downloads']['time_window'].days)..(Date.today)).order('owned_products.created_at DESC')
}
def active_lessons
owned_lessons.active_purchase_scope
end
这是我得到的错误:
ruby-1.8.7-p334 :005 > User.find_by_username('joeblow').active_lessons
NoMethodError: undefined method `active_purchase_scope' for #<User:0x1051a26c8>
da
This is my association and scope setup:
has_many :owned_products
has_many :owned_lessons, :through => :owned_products, :source => :lesson, :conditions => "owned_products.product_type = 'Lesson'"
scope :active_purchase_scope, lambda {
where('owned_products.created_at' => (Date.today - CONFIG['downloads']['time_window'].days)..(Date.today)).order('owned_products.created_at DESC')
}
def active_lessons
owned_lessons.active_purchase_scope
end
This is the error I get:
ruby-1.8.7-p334 :005 > User.find_by_username('joeblow').active_lessons
NoMethodError: undefined method `active_purchase_scope' for #<User:0x1051a26c8>
da
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
范围可以被视为类方法,关联可以被视为实例方法。在您的代码示例中,
owned_lessons
方法返回一个数组对象。您无法在数组对象(或 User 对象)上调用active_purchase_scope
,因为该范围只能在 Model 类上调用(即在您的情况下User.active_purchase_scope
>)您可以通过在
Lesson
模型上添加范围来解决此问题,并按如下方式重写 User 类:
owned_lessons
返回一个匿名范围Lesson
模型,因此我们可以将其与同一模型中的范围active_purchase_scope
链接起来。A
scope
can be treated as a class method and anassociation
can be treated as an instance method. In your code sample, theowned_lessons
method returns an array object. You can't callactive_purchase_scope
on the array object (or User object for that matter) as the scope can only be invoked on the Model class (i.e. in your caseUser.active_purchase_scope
)You can address this issue by adding the scope on the
Lesson
modelAnd rewrite the User class as follows:
The
owned_lessons
returns an anonymous scope on theLesson
model, hence we can chain it with the scopeactive_purchase_scope
from the same model.