2012-11-13 67 views
0

必须一直在问这个问题已经万次,但我无法找到答案:(Rails的嵌套协会搜索

假设我有3种型号:

class Country 
    has_many :cities 
end 

class City 
    has_many :companies 
end 

class Company 
    belongs_to :city 
end 

我可以取公司在给定城City.first.companies,但我想是能够给所有的公司为获取给定的国家,像Country.first.companies

我能做到的,是在Country模型编写方法:

def companies 
    @companies = [] 
    cities.all.each{ |c| @companies << c.companies unless c.companies.empty? } 
    @companies 
end 

但它返回公司对象数组的数组。我本来还添加country_id列作为FK的国家模型,如

class Country 
    has_many :cities 
    has_many :companies 
end 

class Company 
    belongs_to :city 
    belongs_to :country 
end 

,但看起来不很干。

我想接收给定国家的公司对象数组。我很确定有一个Rails的方式来实现这一点。它会是什么?

谢谢!

回答

1

使用has_many through关联。

class Country 
    has_many :companies, :through => :cities 

现在您可以使用Country.last.companies

+0

哦,亲爱的......这很明显,我只是不知道':通过'协会这样工作...... – paulus