我有相关的模型如下:
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/