简体   繁体   English

Rails属于两个模型之一

[英]Rails belongs_to one of two models

I'm working with two different models Person and Organization . 我正在使用两种不同的模式PersonOrganization Among many other attributes, both a Person and Organization can be a Contractor . 在许多其他属性中, PersonOrganization都可以是Contractor If I was working with just the Person model and wanted to store contractor information I would say that Contractor belongs_to :person and be done with it. 如果我只使用Person模型,并想存储承包商信息,我会说Contractor belongs_to :person并完成它。 However this seems like Contractor belongs to two other models. 但是,这似乎似乎Contractor属于其他两个模型。

I searched around on google and found a lot of info about how to assign ownership to two different models at once. 我在Google上四处搜寻,发现了很多有关如何一次将所有权分配给两个不同模型的信息。 (For example a Sale must belong to both a Buyer and a Seller .) But in my situation a Contractor is EITHER a Person or an Organization . (例如, Sale必须同时属于BuyerSeller 。)但在我看来, ContractorPerson还是Organization Is there any way to elegantly store Contractor information for both models in the same table? 有什么方法可以在同一个表中优雅地存储两个模型的Contractor信息?

If not, I figure I can always make two different contractor tables, but I figured this might be an opportunity to learn something. 如果没有,我认为我总是可以制作两个不同的承包商表,但是我认为这可能是学习一些东西的机会。 Many thanks in advance. 提前谢谢了。

Maybe you can try this. 也许您可以尝试一下。 Rails provide polymorphic-associtions . Rails提供了多态关联 You can try to build one model named ContractorInfo belongs to Contractable(use polymorphic: true), then Person has_one ContractorInfo as contractable, Organization has_one ContractorInfo as Contractable. 您可以尝试构建一个名为ContractorInfo的模型,该模型属于Contractable(使用多态性:true),然后将Person has_one ContractorInfo视为可收缩,将组织has_one ContractorInfo视为可收缩。

I agree with ShallmentMo, but as additional, You could define something like this: 我同意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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM