HABTM Polymorphic Relationship

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.

Leave a Comment