首页 文章

如何“利用”已存储在数据库中的关系数据?

提问于
浏览
3

我正在使用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

但是,为了存储更少的数据库数据,我想我可能"use"已经存储在 Region 表中的数据,因为一个城市属于一个区域,而该区域又属于一个国家(这意味着一个城市属于一个国家)但是,在这种情况下,我不知道如何正确地声明 CityCountry 的ActiveRecord关联,以便"exploit"提到"through" Region 模型类隐含的关系信息 .

我该怎么办?


注意:我"forcing"在 City 模型类中声明了 belongs_to :country ActiveRecord关联,因为我想使用RoR :counter_cache功能(仅适用于 belongs_to 关联)来计算一个国家/地区的城市 .

2 回答

  • 1

    使用:through选项 . 正如我在下面的答案中看到的那样(顺便说一下,这是正确的),你只需要添加:

    has_one :country, :through => :region
    

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

    has_many :cities, :through => :regions
    

    然后你可以拥有你的计数专栏

  • 1

    根据rails文档,您可以在 has_one 关系上指定 :through 选项:

    :through指定用于执行查询的连接模型 . 以下选项:class_name,:primary_key和:foreign_key将被忽略,因为关联使用源反射 . 您只能通过连接模型上的has_one或belongs_to关联使用:through查询 .

    所以,你想要的是将 has_one :country, :through => :region 添加到 City .

相关问题