Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HABTM Polymorphic Relationship

I'm pretty new to Rails, and i'm trying to do a polymorphic HABTM relationship. The problem is that I have three models that I want to relate.

The first one is the Event model and then are two kind of attendees: Users and Contacts.

What I want to do is to be able to relate as an attendee both users and contacts. So, what i have right now in my code is:

Event Model

has_and_belongs_to_many :attendees, :polymorphic => true

User Model

has_and_belongs_to_many :events, :as => :attendees

Contact Model

has_and_belongs_to_may :events, :as => :attendees
  1. How the HABTM table migration needs to be? I'm a little confused and i have found no help on that.
  2. Is it going to work?
like image 815
Mateus Pinheiro Avatar asked Aug 06 '11 04:08

Mateus Pinheiro


1 Answers

No, you can't do that, there's no such thing as a polymorphic has_and_belongs_to_many association.

What you can do is create a middle model. It would probably be something like this:

class Subscription < ActiveRecord::Base
  belongs_to :attendee, :polymorphic => true
  belongs_to :event
end

class Event < ActiveRecord::Base
  has_many :subscriptions
end

class User < ActiveRecord::Base
  has_many :subscriptions, :as => :attendee
  has_many :events, :through => :subscriptions
end

class Contact < ActiveRecord::Base
  has_many :subscriptions, :as => :attendee
  has_many :events, :through => :subscriptions
end

This way the Subscription model behaves like the link table in a N:N relationship but allows you to have the polymorphic behavior to the Event.

like image 65
Maurício Linhares Avatar answered Sep 23 '22 23:09

Maurício Linhares