d_a_n
d_a_n

Reputation: 317

Rails 4 activerecord polymorphic many-to-many

I have an Activity model, along with models for Group and Individual.

These aren't associated in any way at the moment, but I'm looking at how I can set up the necessary associations in Active Record.

An Activity will have many participants, both Groups and Individuals. A Group or Individual might participate in many Activities.

It looks as though a polymorphic ActivityParticipant association might do this but it needs to be many to many on both sides.

I probably need a table that has

activity_id activity_participant_type activity_participant_id

If be grateful for any advice on how activerecord handles this and the association definitions.

Thanks in advance Dan

Upvotes: 1

Views: 205

Answers (1)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42909

first the models

def ActivityParticipant < ActiveRecord::Base
  belongs_to :participant, polymorphic: true
  belongs_to :activity
end

def Groups < ActiveRecord::Base
  has_many :activity_participants, as: :participant
  has_many :activities, through: :activity_participants
end

def Individual < ActiveRecord::Base
  has_many :activity_participants, as: :participant
  has_many :activities, through: :activity_participants
end

As for the migration

def change
  create_table :activity_participants do |t|
    t.references :participant, polymorphic: true, index: true
    t.references :activity
    t.timestamps
  end
end

As for the final schema it would be

# activity_participants
activity_id | participant_type | participant_id

I think this should work, no need to add any references in any of the other tables.

Upvotes: 2

Related Questions