首页 > 解决方案 > 同一个类的多个 belongs_to 关联

问题描述

我一直在这里寻找答案,我觉得我已经接近了,但大多数其他示例与我想要做的不太匹配。

我有一个“人”类和一个“区”类。Each district has many people -- one of those people is an incumbent (elected official), and the others are candidates. 这部分工作正常且相当简单。在地区的“显示”页面的底部,我列出了为该地区竞选的所有相关人员,现任者以粗体显示(如果他们在选票上)。再次,工作很棒。

但是:在某些情况下,一个人可能是一个办公室的现任者(因此他们有那个 District_ID),但他是另一个办公室的候选人(例如,某个城市的现任市长,但也在竞选立法机构以提升链条)。

因此,我试图弄清楚如何最好地让一个人在这种情况下出现在他们目前任职的地区以及他们正在寻求职位的地区。

如果有人能引导我走向正确的关联方法,我将不胜感激!

标签: ruby-on-rails

解决方案


我将采用以下假设:

  1. 每个区只有一个现任者
  2. 每个人只能是一个区的候选人
  3. 您可以在您任职的不同地区成为候选人

在这种情况下,我将系统设置如下:

belongs_to :district, inverse_of: :candidates, class_name: 'District', optional: true, 
has_one :incumbent_district, inverse_of: :incumbent, class_name: 'District', optional: true
has_many :candidates, inverse_of: :district, class_name: 'Person'
belongs_to :incumbent, inverse_of: :incumbent_district, class_name: 'Person', foreign_key: 'incumbent_id', optional: true

在数据库中:

create_table 'people' do |t|
  # (...)

  t.integer "district_id"
  t.index "district_id"
end

create_table 'districts' do |t|
  # (...)

  t.integer "incumbent_id"
  t.index "incumbent_id"
end

之后,您应该能够:

p = Person.first
p.districts # returns all districts where the person is a candidate
p.incumbent_district # returns the district where the candidate is the incumbent, or `nil` if there isn't

d = District.first
d.incumbent # returns the incumbent person
d.candidates # returns the candidates for this district

笔记:

  1. has_one您可以为现任者切换 has_one/belongs_to - 您拥有的位置和位置都没有关系,belongs_to因为它是 1-1 关系。但是,通常您会将 放到belongs_to通常会有链接has_one的类中,并将 放到类中,这是可选的。由于每个地区可能都有现任者,但大多数人只是候选人而不担任公职,这将是真的。
  2. 您可能会optional: true从上面删除一些标记,例如,如果所有地区都将始终有一个现任者,您可以将其从 District 类中删除。
  3. 您可能需要调查是否has_and_belongs_to_many有一个人可以成为复合区的候选人。这样做时,您还可以在地区和人员之间的连接表中标记现任者,这将允许更复杂的场景(例如,多个现任者、历史数据等)

推荐阅读