1

協會我在一個小問題面前的時候,我嘗試有一個polymophic有通過關聯許多:的Rails:HAS_MANY通過polymophic找不到模型

post.rb

的has_many :類別,如:categorizable,通過:分類已

category.rb

的has_many:categorizables,通過:分類已依賴:破壞

event.rb

的has_many:類別,如:categorizable,通過:分類已

categorization.rb

belongs_to:categorizable,:polymorphic => true

belongs_to的:類

我的遷移:

DEF改變

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 

問題:

我這個錯誤:

找不到關聯:模型分類已發表

或當我嘗試在類別

找不到關聯:模型類別分類已

有誰知道問題在哪裏?

+3

這是什麼問題?任何錯誤? –

+0

打擾我!我編輯我的問題! – p0k3

回答

2

你需要指定:categorizations協會還,在CategoryPostEvent。此外,你的as選項應該去categorizations協會,因爲這是你的多態性。

Post類:

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

您應修改以類似的方式Event類。

Category類:

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

謝謝你LOT !!! – p0k3