Search code examples
ruby-on-railsrubyactiverecordhas-many-throughpolymorphic-associations

Rails : Has_Many Through polymophic Could not find the association in model


I'm in front of a little problem, I try to have a polymophic has many through association :

post.rb

has_many :categories, as: :categorizable, through: :categorizations

category.rb

has_many :categorizables, through: :categorizations, dependent: :destroy

event.rb

has_many :categories, as: :categorizable, through: :categorizations

categorization.rb

belongs_to :categorizable, :polymorphic => true

belongs_to :category

My migration :

def change

create_table :categories do |t|
  t.string :name

  t.timestamps
end

create_table :categorizations do |t|
  t.references :category

  t.integer :categorizable_id, :polymorphic => true
  t.string :categorizable_type, :polymorphic => true

  t.datetime :created_at
end

add_index :categorizations, :category_id   

end

the problem :

I got this error :

Could not find the association :categorizations in model Post

Or when I try in category

Could not find the association :categorizations in model Category

Does anyone know where is the problem?


Solution

  • You need to specify :categorizations association also, in Category, Post and Event. Also, your as option should go to categorizations association, since this is where you have polymorphism.

    Post class:

    class Post < ActiveRecord::Base
      has_many :categorizations, as: :categorizable
      has_many :categories, through: :categorizations
      # ...
    end
    

    You should modify Event class in similar manner.

    Category class:

    class Category < ActiveRecord::Base
      has_many :categorizations
      has_many :categorizables, through: :categorizations, dependent: :destroy
      # ...
    end