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])
然后,即使Item.first.country =&gt;,Item.american也会一直空着。 '美国'
顺便说一下,在Rails 2.3.4版本中我们有:
named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'United States' }
这就像宣传的那样有效。
答案 0 :(得分:2)
你忘了复数表名,我也认为包含的顺序和可能重要的地方。当指定关联条件时,也建议使用连接:
scope :american, joins(:users, :countries).where('countries.name' => 'United States')
如果您还想使用包括:
scope :american, includes(:users, :countries).where('countries.name' => 'United States')