我有乡村,城市,商店的模特
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 {x、c、x、c.shops },但这不是activerecord对象。
我考虑过在商店模型上添加country_id并设置has_many关系,但我认为这不是最好的方法。
发布于 2014-03-04 03:01:51
在国家中,添加一个has_many :通过关系:
class Country < ActiveRecord::Base
has_many :cities
has_many :shops, through: :cities
end现在,您可以编写country.shops并接收一个适当的ActiveRecord关系,您可以在其中说一些类似country.shops.where name:"Nieman Marcus"和其他类似查询的内容。
发布于 2014-03-04 02:24:36
您可以在类国家中开发一种方法。
def all_shops
self.cities.collect { |c| c.shops }
end您可以使用Mongoid::Tree
def all_shops
Shop.where(:parent_ids => self.id)
endhttps://stackoverflow.com/questions/22161543
复制相似问题