如何在 Rails 中为具有单一 table 继承的人和公司建模?

How to model people and companies with single table inheritance in Rails?

在我的发票应用程序中 invoices 可以发送给 companyperson。据我了解,这是 Rails' 单一 table 继承 (STI) 的一个很好的用例。由于这两种类型共享许多属性和功能,我认为 super-class Recipient 可能是一个不错的选择:

class Recipient < ActiveRecord::Base 
end

class Company < Recipient
  has_many :people
end

class Person < Recipient
  belongs_to :company
end

我也明白我需要 Recipient 模型中的属性 type

唯一让我困扰的是 person 可能(或可能不)属于 company。如何在 Rails 中建模?通常,我只是将另一个数据库字段 company_id 添加到 people table。但是这里只有一个 table (recipients)。那么如何才能做到呢?

感谢您的帮助。

class Recipient < ActiveRecord::Base 
end

class Company < Recipient
  has_many :people, class_name: "Recipient", foreign_key: 'parent_id' 
end

class Person < Recipient
  belongs_to :company, class_name: "Recipient", foreign_key: 'parent_id'
end

只需将 parent_id 添加到收件人迁移。 这就是它简单快速,你得到你想要的一个模型两个 STI 和 has_manybelongs_tocompanyperson 之间。

结构可能如下所示:

class Recipient < ActiveRecord::Base 
  has_many :invoices
end

class Company < Recipient
  has_many :people
end

class Person < Recipient
  belongs_to :company
end

class Invoice < ActiveRecord::Base
  belongs_to :recipients
end

# Schema
create_table "invoices", force: :cascade do |t|
  t.integer "recipient_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.index ["recipient_id"], name: "index_invoices_on_recipient_id"
end

create_table "recipients", force: :cascade do |t|
  t.integer "company_id"
  t.string "type"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

我刚在控制台试过:

> Recipient.all
 => [#<Company:0x007fd55d797220
  id: 1,
  company_id: nil,
  type: "Company",
  created_at: Fri, 04 Aug 2017 10:57:41 UTC +00:00,
  updated_at: Fri, 04 Aug 2017 10:57:41 UTC +00:00>,
 #<Person:0x007fd55d796730
  id: 2,
  company_id: 1,
  type: "Person",
  created_at: Fri, 04 Aug 2017 10:57:41 UTC +00:00,
  updated_at: Fri, 04 Aug 2017 10:57:41 UTC +00:00>,
 #<Person:0x007fd55d796208
  id: 3,
  company_id: nil,
  type: "Person",
  created_at: Fri, 04 Aug 2017 10:57:41 UTC +00:00,
  updated_at: Fri, 04 Aug 2017 10:57:41 UTC +00:00>]

> Person.last.company
  Person Load (0.2ms)  SELECT  "recipients".* FROM "recipients" WHERE "recipients"."type" IN ('Person') ORDER BY "recipients"."id" DESC LIMIT ?  [["LIMIT", 1]]
 => nil

> Person.first.company
  Person Load (0.2ms)  SELECT  "recipients".* FROM "recipients" WHERE "recipients"."type" IN ('Person') ORDER BY "recipients"."id" ASC LIMIT ?  [["LIMIT", 1]]
  Company Load (0.2ms)  SELECT  "recipients".* FROM "recipients" WHERE "recipients"."type" IN ('Company') AND "recipients"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
 => #<Company id: 1, company_id: nil, type: "Company", created_at: "2017-08-04 10:57:41", updated_at: "2017-08-04 10:57:41">