HABTM Polymorphic Relationship

前端 未结 2 1949
半阙折子戏
半阙折子戏 2020-12-01 09:13

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

2条回答
  •  粉色の甜心
    2020-12-01 10:01

    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.

提交回复
热议问题