简体   繁体   中英

Can a model belong to either one of two other models

I will try to explain this as best as I can.

I have 3 models.

DistributionEvent PrimaryAssignment SecondaryAssignment

I need the DistributionEvent to belong_to either a PrimaryAssignment or a SecondaryAssignment and show on the same column in the database.

So something like this

class DistributionEvent < ActiveRecord::Base
 belongs_to :primaryassignment
 belongs_to :secondaryassignment
end

class PrimaryAssignment < ActiveRecord::Base
 has_many :distribution_event
end

class SecondaryAssignment < ActiveRecord::Base
 has_many :distribution_event
end

But the DistributionEvent should only have one column (assignment or something) in the table that points to either primaryassignments or secondaryassignments.

I hope that make sense.

Anyone have any clue on how to achieve this efficiently?

Thanks!

Yes, with polymorphic associations. The documentation can be found here: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

class DistributionEvent < ActiveRecord::Base
 belongs_to :assignment, polymorphic: true
end

class PrimaryAssignment < ActiveRecord::Base
 has_many :distribution_events, as: :assignment
end

class SecondaryAssignment < ActiveRecord::Base
 has_many :distribution_events, as: :assignment
end

Make sure to also add a column for the type:

class AddAssignmentTypeToDistributionEvent < ActiveRecord::Migration
  def change
    add_column :distribution_events, :assignment_type, :string
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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