【发布时间】:2015-11-29 15:02:54
【问题描述】:
我有以下相关模型:
Country
has_many :states
State
belongs_to :country
has_many :counties
County
belongs_to :State
has_many :municipalities
has_many :cities, through: :municipalities
City
has_many :municipalities
has_many :counties, through: :municipalities
Municipality
belongs_to :county
belongs_to :city
我希望能够调用@country.cities 并让它通过其相关对象返回属于一个国家的所有城市。
有没有人看到或写过一个好帮手?还是有这样做的传统方法?现在我所拥有的最好的是像
def country_cities(country)
country.municipalities.each do |municipality|
municipality.city
end
end
我对我可能遗漏了一些简单的事实持开放态度,但我已经详细阅读了活动记录文档,并且似乎活动记录在构建 SQL 查询时使用了 belongs_to 帮助器,所以 has_many 到关系打破了向下的“链条”,您必须像这样@country.municipalities.individual_municipality.cities
我正在寻找更优雅/更简单的解决方案
与实际查询相关: 由于城市不属于县或直辖市,因此没有城市 ID 或县 ID。他们有_many :counties, through: :municipalities
我想通过直辖市查询所有拥有_a_county 的城市。按照惯例,城市不应该有 cityity_ids。如果我分配一个,我应该能够像这样查询所有拥有_a_county 的城市的数据库:
我愿意
# find cities
SELECT `cities`.* FROM `cities`
# where municipality_ids match any of the returned municipalities.
INNER JOIN `municipalities` ON `cities`.`municipality_id` = `municipalities`.`id`
#inner join may be wrong here. I'm not sure exactly what that does; I just mimicked the other queries' syntax assuming it will check the records in the 'assemblies' table for a quantity_id.
# where county_ids match any of the returned counties.
INNER JOIN `counties` ON `municipalities`.`county_id` = `counties`.`id`
# where state_ids match any of the returned states
INNER JOIN `states` ON `developments`.`state_id` = `states`.`id`
# where state.country_id = params[:id]
WHERE `states`.`country_id` = 1
上面的查询需要城市有一个 Municipality_id 才能工作,但我有点担心这样做会在活动记录中引起一些奇怪的行为。
感谢任何反馈。谢谢!
【问题讨论】:
标签: ruby-on-rails rails-activerecord relationship has-many-through has-many