的結構看起來是這樣的:
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">
另外值得一提的是用於製作公司和個人不同的模型完全關切,包括被稱爲(例如)可開票或不可開票或沿着這些行的擔憂,以保持發票邏輯。不過,STI在這裏也是一個很好的用例。讓我在一秒鐘內寫出答案,爲STI解決方案。 –