1

假设我有类似的东西

Country has_many :cities

并且模型City有一个属性council_id。只有一个实例Country,检索包含所有相关内容的集合的最佳方法是什么Councils

我知道这可以很容易地完成,将Country实例传递给某个方法并迭代,council_ids但我想知道是否有更优雅的方法?

谢谢

4

3 回答 3

5

如果城市有

belongs_to :country
belongs_to :council

那么国家可以有

has_many :cities
has_many :councils, :through => :cities

然后你可以做some_country.councils。这在幕后构造了一个连接查询来加载相关联的委员会。如果一个城市有很多议会,这仍然有效 -has_many :through可以解决这个问题

于 2012-06-24T09:19:52.143 回答
0

这是我能想到的最短方法(假设您已经设置了@country实例):

Council.joins(:city => :countries).where('countries.id = ?', @country.id)

您可能只想country_id为每个委员会保存,但可以通过以下方式更轻松地完成此操作:

@country.councils
于 2012-06-24T08:13:46.110 回答
0

如果理事会是模型,请尝试以下操作:

Council.where(city_id: @country.cities)

如果council_id 是城市模型的属性:

@country.cities.map {|c| c.council_id}
于 2012-06-24T08:57:37.317 回答