gpt4 book ai didi

ruby-on-rails - 如何将 "exploit"关系数据存入数据库?

转载 作者:数据小太阳 更新时间:2023-10-29 08:05:06 24 4
gpt4 key购买 nike

我正在使用 Ruby on Rails v3.2.2。我有以下模型类

class Country < ActiveRecord::Base
has_many :regions, :foreign_key => 'country_id'
end

class Region < ActiveRecord::Base
belongs_to :country, :foreign_key => 'country_id'
has_many :cities, :foreign_key => 'region_id'
end

class City < ActiveRecord::Base
belongs_to :region, :foreign_key => 'region_id'
end

我想创建一个City belongs_to :country

我知道最简单的方法是将 country_id 数据库表列添加到 City 数据库表并声明相关的 ActiveRecord 关联,这样:

class Country < ActiveRecord::Base
# ...
has_many :cities, :foreign_key => 'country_id'
end

class City < ActiveRecord::Base
# ...
belongs_to :country, :foreign_key => 'country_id'
end

但是,为了存储较少的数据库数据,我想我可以“使用”已经存储在Region 表中的数据因为一个城市属于一个地区又属于一个国家(这意味着一个城市属于一个国家)但是,在这种情况下,我不知道如何为 City 正确声明 ActiveRecord Associations和 Country 以便“利用”提到的关系信息隐式地“通过”Region 模型类呈现。

我应该如何进行?


注意:我“强制”在 City 模型类中声明 belongs_to :country ActiveRecord 关联,因为我想使用RoR :counter_cache功能(适用于 belongs_to 协会)以计算一个国家/地区中存在的城市。

最佳答案

使用 :through 选项。正如我在下面答案的评论中看到的那样(顺便说一下,这是正确的),您只需添加以下内容:

has_one :country, :through => :region

到您的 City 类。如果您想为城市应用国家/地区的 counter_cache,那么您还必须在国家/地区类中建立关系,如下所示:

has_many :cities, :through => :regions

然后你可以有你的计数列

关于ruby-on-rails - 如何将 "exploit"关系数据存入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13223482/

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