首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >has_many与has_many关系

has_many与has_many关系
EN

Stack Overflow用户
提问于 2014-03-04 02:15:58
回答 2查看 170关注 0票数 0

我有乡村,城市,商店的模特

代码语言:javascript
复制
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关系,但我认为这不是最好的方法。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-04 03:01:51

在国家中,添加一个has_many :通过关系:

代码语言:javascript
复制
class Country < ActiveRecord::Base
  has_many :cities
  has_many :shops, through: :cities
end

现在,您可以编写country.shops并接收一个适当的ActiveRecord关系,您可以在其中说一些类似country.shops.where name:"Nieman Marcus"和其他类似查询的内容。

票数 1
EN

Stack Overflow用户

发布于 2014-03-04 02:24:36

您可以在类国家中开发一种方法。

代码语言:javascript
复制
def all_shops
  self.cities.collect { |c| c.shops }
end

您可以使用Mongoid::Tree

代码语言:javascript
复制
def all_shops
  Shop.where(:parent_ids => self.id)
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22161543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档