![](/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.