![](/img/trans.png)
[英]In Rails models, can I change belongs_to to has_one and has_one to belongs_to?
[英]Rails belongs_to one of two models
我正在使用兩種不同的模式Person
和Organization
。 在許多其他屬性中, Person
和Organization
都可以是Contractor
。 如果我只使用Person
模型,並想存儲承包商信息,我會說Contractor
belongs_to :person
並完成它。 但是,這似乎似乎Contractor
屬於其他兩個模型。
我在Google上四處搜尋,發現了很多有關如何一次將所有權分配給兩個不同模型的信息。 (例如, Sale
必須同時屬於Buyer
和Seller
。)但在我看來, Contractor
是Person
還是Organization
。 有什么方法可以在同一個表中優雅地存儲兩個模型的Contractor
信息?
如果沒有,我認為我總是可以制作兩個不同的承包商表,但是我認為這可能是學習一些東西的機會。 提前謝謝了。
也許您可以嘗試一下。 Rails提供了多態關聯 。 您可以嘗試構建一個名為ContractorInfo的模型,該模型屬於Contractable(使用多態性:true),然后將Person has_one ContractorInfo視為可收縮,將組織has_one ContractorInfo視為可收縮。
我同意ShallmentMo,但除此之外,您可以定義以下內容:
Models
class Contractor < ActiveRecord::Base
belongs_to :contractable, polymorphic: true
...
end
class Person < ActiveRecord::Base
...
has_many :contractors, as: :contractable
...
end
class Organization < ActiveRecord::Base
...
has_many :contractors, as: :contractable
...
end
Migrations
create_table :contractors , force: true do |t|
t.references :contractable, polymorphic: true, index: true
...
t.timestamps null: false
end
Usage
def create
@contractor = Contractor.new(params[:contractor])
contractable = params[:contractor][:contractable].split(":")
@contractor.contractable_type = contractable[0] # String: 'Person' or 'Organization'
@contractor.contractable_id = contractable[1].to_i # Integer: id of 'Person' or 'Organization'
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.