2010-03-24 63 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

相關問題