2010-03-24 65 views
3

我正在使用Rails 2.3.5。嵌套has_many

Class User < ActiveRecord::Base 
    has_many :phones 
end 

class Phone < ActiveRecord::Base 
    has_many :frequency_bands 
end 

我想获取用户的所有frequency_bands。我知道我可以为用户编写一个def freq_bands的方法,但我想知道是否可以为用户使用has_many freq_bands。通过这种方式,我可以连接电话。

我想吃点什么是

class User < ActiveRecor::Base 
    has_many :frequence_bands, :through => phones 
end 

我认为这是可能使用这个插件http://github.com/ianwhite/nested_has_many_through

但是,如果可能,我想避免使用其他插件有嵌套的has_many和单纯依靠轨道。

+1

不轨道已经这样做了吗?它与您所描述的完全一样。 'has_many:frequency_bands,:through =>:phones'。 – jamuraa 2010-03-24 14:40:18

回答

7
class User < ActiveRecord::Base 
    has_many :phones 
    has_many :frequence_bands, :through => :phones 
end 

工作得很好。你只需要嵌套的has_many_through插件,如果手机本身也是has_many_through关系,它不在你的例子中。

(责任编辑:不要忘记“:”在最后一个属性的前面)

+0

是真的,或者如果你想*另一个*级别的深度。当然,太多的关卡对应用程序来说并不好。我写了一篇博客文章,介绍如何做到这一点:http://kconrails.com/2010/01/28/nesting-has_many-through-relationships-in-ruby-on-rails/ - 谨慎使用! – 2010-10-23 03:13:04

+0

仍然适用于Rails 4.注意:如果您为关联使用不同的名称,请务必指定一个:source。例如'has_many:my_frequency_bands,通过::phones,source :: frequency_bands' – robertwbradford 2014-03-13 20:00:19

相关问题