基于 has_one :through 关系在 Rails 3 中创建作用域
Rails 3.0.3 和 Ruby 1.9.2
我有以下类
class item < ActiveRecord::Base
belongs_to :user
has_one :country, :through => :user
..
end
所以 itemA.country 产生“美国”
问题是如何为美国用户拥有的所有项目创建一个(命名)范围
当我尝试类似的操作时:
scope :american, where('countries.name' => 'United States').includes([:user, :country])
then Item即使 Item.first.country => ,.american 仍然会返回空。 “美国”
顺便说一句,在 Rails 2.3.4 版本中,我们有:
named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'United States' }
这正如广告中所宣传的那样。
Rails 3.0.3 and Ruby 1.9.2
I have the following class
class item < ActiveRecord::Base
belongs_to :user
has_one :country, :through => :user
..
end
So itemA.country yields "United States"
The question is how do I created a (named) scope for all items owned by US users
When I try something like:
scope :american, where('countries.name' => 'United States').includes([:user, :country])
then Item.american keeps coming back empty even when Item.first.country => 'United States'
Incidentally, in the Rails 2.3.4 version we had:
named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'United States' }
And that worked as advertised.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您忘记了表名的复数形式,我还认为 include 的顺序和 where 可能很重要。还建议在指定关联条件时使用联接,如下所示:
如果您仍希望使用包含:
You forgot to pluralize the table names, I also think the ordering of include and where may matter. It's also recommended to use a join instead when specifying conditions on associations like so:
If you'd prefer to still use includes: