2014-03-04 165 views
0

我已经国家,城市,网店模特的has_many和的has_many关系

class Country < ActiveRecord::Base 
    has_many :cities 
end 

class City < ActiveRecord::Base 
    belongs_to :country 
    has_many :shops 
end 

class Shop < ActiveRecord::Base 
    belongs_to :city 
end 

我怎样才能得到的ActiveRecord country.shops? (得到所有国家的商店)

我通常使用Country.cities.collect {| c | c.shops} 但这不是主动记录对象。

我已经考虑在shop model上添加country_id并设置has_many关系,但我认为这不是最好的方法。

回答

1

在国家,加入的has_many:通过关系:

class Country < ActiveRecord::Base 
    has_many :cities 
    has_many :shops, through: :cities 
end 

现在您可以编写country.shops并获得适当的ActiveRecord关系,您可以在其中说明诸如之类的内容和其他此类查询。

0

您可以在类国家一变形点焊方法

def all_shops 
    self.cities.collect { |c| c.shops } 
end 

你ALSE可以使用Mongoid ::树

def all_shops 
    Shop.where(:parent_ids => self.id) 
end 
+0

thx for comment,但它返回的数组不是AR – blankammo