2014-01-06 64 views
0

我有一對夫婦模型獲取所有記錄兩個`的has_many,through`關係遠

class AAA < ActiveRecord::Base 
    has_many :bbbs, through: :some_other_model 
end 

class BBB < ActiveRecord::Base 
    has_many :cccs, through: :yet_another_model 
end 

假設我要的AAA實例的引用,我怎麼能得到所有CCCs的平面列表,而不訴諸低效的模式,如a.bbbs.map { |x| x.cccs }

回答

2

由於RoR 3.1,您可以嵌套has_many :through關聯。

3.1 release notes來自:

協會用:通過選項現在可以通過或源關聯,包括具有一個 其他協會使用任何關聯作爲 :通過選項和has_and_belongs_to_many關聯。

在您的例子:

class AAA < ActiveRecord::Base 
    has_many :bbbs, through: :some_other_model 
    has_many :cccs, through: :bbbs 
end 

AAA.first.cccs # => [ccc1, ccc2, ...] 
+0

我已經嘗試過這一點,它沒有workk。也許這只是一個愚蠢的語法錯誤,我沒有注意到。我會再嘗試。 – Jeff

+0

我不完全確定這次有什麼不同,但它現在似乎工作得很好。謝謝! – Jeff

相關問題