ruby-on-rails - 同一个类的多个 belongs_to 关联
问题描述
我一直在这里寻找答案,我觉得我已经接近了,但大多数其他示例与我想要做的不太匹配。
我有一个“人”类和一个“区”类。Each district has many people -- one of those people is an incumbent (elected official), and the others are candidates. 这部分工作正常且相当简单。在地区的“显示”页面的底部,我列出了为该地区竞选的所有相关人员,现任者以粗体显示(如果他们在选票上)。再次,工作很棒。
但是:在某些情况下,一个人可能是一个办公室的现任者(因此他们有那个 District_ID),但他是另一个办公室的候选人(例如,某个城市的现任市长,但也在竞选立法机构以提升链条)。
因此,我试图弄清楚如何最好地让一个人在这种情况下出现在他们目前任职的地区以及他们正在寻求职位的地区。
如果有人能引导我走向正确的关联方法,我将不胜感激!
解决方案
我将采用以下假设:
- 每个区只有一个现任者
- 每个人只能是一个区的候选人
- 您可以在您任职的不同地区成为候选人
在这种情况下,我将系统设置如下:
- 人
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
笔记:
has_one
您可以为现任者切换 has_one/belongs_to - 您拥有的位置和位置都没有关系,belongs_to
因为它是 1-1 关系。但是,通常您会将 放到belongs_to
通常会有链接has_one
的类中,并将 放到类中,这是可选的。由于每个地区可能都有现任者,但大多数人只是候选人而不担任公职,这将是真的。- 您可能会
optional: true
从上面删除一些标记,例如,如果所有地区都将始终有一个现任者,您可以将其从 District 类中删除。 - 您可能需要调查是否
has_and_belongs_to_many
有一个人可以成为复合区的候选人。这样做时,您还可以在地区和人员之间的连接表中标记现任者,这将允许更复杂的场景(例如,多个现任者、历史数据等)
推荐阅读
- reporting-services - 我是 SSRS 的管理员,但无权更改订阅所有者
- scala - 在 scala 中创建元组时类型绑定错误
- c# - C# - 添加 DataGridView 时出现 SQL 查询舍入问题
- javascript - Django - 如何在 Mapbox 地图上显示 GeoJSON?
- ios - 如何在 Swift 中实现简单的 MVC 设计模式?
- java - 主类不是超类有什么问题?
- python - 如何在 argparse 中为可选参数附加默认值?
- azure - Connect-AzAccount - 如何避免 azure 设备身份验证?
- python - 注销/登录视图的问题
- botframework - 如何将 Microsoft 健康机器人集成到 Web 应用程序