I'm in front of a little problem, I try to have a polymophic has many through association :
has_many :categories, as: :categorizable, through: :categorizations
has_many :categorizables, through: :categorizations, dependent: :destroy
has_many :categories, as: :categorizable, through: :categorizations
belongs_to :categorizable, :polymorphic => true
belongs_to :category
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
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?
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