gpt4 book ai didi

ruby-on-rails - 多层次的 Rails 关联

转载 作者:行者123 更新时间:2023-12-04 03:36:34 24 4
gpt4 key购买 nike

我对 Rails 比较陌生,并且正在从事一个涉及多个“嵌套”数据级别的项目。我在建立正确的关联时遇到了问题,因此我可以将模型 3 的所有子元素提高到更高的级别。以下是模型示例:

class Country < ActiveRecord::Base
has_many :states
end

class State < ActiveRecord::Base
belongs_to :country
has_many :cities
end

class City < ActiveRecord::Base
belongs_to :state
has_many :people
end

class Person < ActiveRecord::Base
belongs_to :city
end

我在 Country 中实现了一个关系型号, has_many :cities, :through => :states并尝试调用 Country.first.cities.all ,这有效。但是,当我尝试 Country.first.cities.all.people.all 时,我无法访问给定国家/地区的所有人。在 People Controller 。

处理这种关联情况的最佳方法是什么?我是否应该为每个子表添加一个外键,例如 country_id ,这样我就可以得到所有的 PeopleCountry ?任何建议,将不胜感激。

最佳答案

原因是 Country.first.cities.all 是一个数组,它的每个元素都有方法 people,而不是整个城市的集合。您会注意到这是有效的:

Country.first.cities.first.people.all

因为第一国第一城有民法。要获取一个国家/地区所有人的列表,您可以在单个查询中执行以下操作:
People.joins(:city => {:state => :country})
.where(:country => {:id => Country.first.id}).all

关于ruby-on-rails - 多层次的 Rails 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5134723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com