mysql - 如何通过 ruby​​ on Rails 中的联接表进行单个查询来检索与模型相关的对象

标签 mysql sql ruby-on-rails has-many-through has-many

我有相关的模型如下:

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之类的东西,并让它通过其相关对象返回属于一个国家/地区的所有城市。如有任何反馈,我们将不胜感激,谢谢!

最佳答案

尝试:

Country
  has_many :states
  has_many :cities, through: :states

State
  has_many :counties
  has_many :cities, through: :counties

关于mysql - 如何通过 ruby​​ on Rails 中的联接表进行单个查询来检索与模型相关的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32441095/

相关文章:

php - 如何汇总 mysql 请求的 ORDER BY 部分中的多个 int 列?

ruby-on-rails - 设计未定义的方法 'registration_path'

ruby-on-rails - 都柏林邮政编码的正则表达式

PHP MySQL 将多个复选框中的值插入到表中的一列中

mysql - 将最新时间戳从一个表复制到另一个表

php - 删除id重复的表中的重复记录

Mysql查询没有按照我的意愿获取数据

mysql - 如果 key 存在则自动更新

mysql - 使用别名更新表

ruby-on-rails - 更正 HAML 以将图像链接到我的 Ruby on Rails 应用程序中的另一个页面