【发布时间】:2019-01-21 15:31:56
【问题描述】:
我很难思考应该如何配置我的表 + 关联。
我有一个Lawsuit 模型。诉讼has_many各方(被告、原告、律师等)。反过来,聚会可以是Person 或Company。最终,我希望能够得到:
- 一个人的诉讼(
@person.lawsuits); - 公司诉讼(
@company.lawsuits);和 - 诉讼当事人 (
@lawsuit.parties),可以是people或companies。
这就是我目前设置表格和模型的方式:
人
| id | fname | lname | date_of_birth |
| -- | ------ | ----- | ------------- |
| 1 | John | Smith | 1974-02-04 |
| 2 | George | Glass | 1963-07-29 |
公司
| id | name | duns | ticker | address |
| -- | --------- | --------- | ------ | ------------ |
| 1 | Acme Inc. | 239423243 | ACME | 123 Main St. |
诉讼
| id | jurisdiction | court | case_no | title |
| -- | ------------ | ----- | ---------- | --------------------------- |
| 1 | federal | SDNY | 18-CV-1234 | Smith v. Glass, Acme, et al |
诉讼当事人
| id | lawsuit_id | person_id | company_id | role |
| -- | ---------- | --------- | ---------- | --------- |
| 1 | 1 | 1 | | plaintiff |
| 2 | 1 | 2 | | defendant |
| 3 | 1 | | 1 | defendant |
# models/lawsuit.rb:
class Lawsuit < ApplicationRecord
has_many :lawsuit_parties
def parties
self.lawsuit_parties
end
def defendants
self.parties(where(lawsuit_parties: {role: 'defendant'})
end
def plaintiffs
self.parties(where(lawsuit_parties: {role: 'plaintiff'})
end
def attorneys
self.parties(where(lawsuit_parties: {role: 'attorney'})
end
end
# models/lawsuit_party.rb
class LawsuitParty < ApplicationRecord
belongs_to :person
belongs_to :company
end
# models/person.rb
class Person < ApplicationRecord
has_many :lawsuit_parties
has_many :lawsuits, through: :lawsuit_parties
end
# models/company.rb
class Company < ApplicationRecord
has_many :lawsuit_parties
has_many :lawsuits, through: :lawsuit_parties
end
任何帮助将不胜感激......
【问题讨论】:
标签: ruby-on-rails ruby activerecord ruby-on-rails-5 polymorphic-associations