2014-03-04 170 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