2011-02-17 56 views
0

的Rails 3.0.3和Ruby 1.9.2创建基于HAS_ONE在Rails 3的一个范围:通过关系

我有下面的类

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.american不断回来空,即使Item.first.country => '美国'

顺便说一下,在Rails的2.3.4版本中,我们有:

named_scope :american, :include => {:user, :country}, :conditions => { 'countries.printable_name' => 'United States' } 

而且像广告一样工作。

+1

略无关,但你应该升级到Rails的3.0。 4,因为这是一个安全发布。 – 2011-02-17 23:37:50

回答

2

你忘了复制表名,我也认为包含的顺序和在哪里可能很重要。它也建议像这样的协会指定条件时使用代替连接:

scope :american, joins(:users, :countries).where('countries.name' => 'United States') 

如果您希望仍然使用包括:

scope :american, includes(:users, :countries).where('countries.name' => 'United States') 
+0

谢谢。它适用于以下内容:范围:american,joins(:user,:country).where('countries.name'=>'United States'),所以我猜表名不需要复数化。 – Andy 2011-02-17 23:58:54

相关问题