Search code examples
ruby-on-railsmodelassociationspolymorphic-associations

How to set up a polymorphic has_many :through?


I'm having trouble figuring out the right way to set this association up.

I have 3 models: Musicians, Bands and Managers. Each of those can have a certain "level" associated with them (stress, happiness, etc).

But I'm not sure how to correctly associated my levels with the other 3.

There needs to be an intermediary model that connects the levels with the different items and sets what the current level is at.

Do I need some sort of has_many :through that's polymorphic? And how on earth do I set that up? Is there some other type of associated I need?

enter image description here

I asked a similar question before but did a thoroughly awful job of explaining what I was trying to do, so this is my second attempt.


Solution

  • ItemLevels needs a type to know what it is associated with:

    class ItemLevel < ActiveRecord::Base
        #  levelable_id   :integer
        #  levelable_type :string(255)
        belongs_to :levelable, :polymorphic => true
        has_many :levels
    end
    
    class Musician < ActiveRecord::Base
        has_many :levelables
    end
    
    class Musician < ActiveRecord::Base
        has_many :levelables
    end
    
    class Manager < ActiveRecord::Base
        has_many :levelables
    end
    

    Level then only needs to know what ItemLevel it is associated with:

    class Level < ActiveRecord::Base
        belongs_to :item_level
    end
    

    If you want to be strict, you should put some validation in you Level model to check it has an ItemLevel and the type being instantiated.