2010-09-11 64 views
3

我有過關係的簡單的has_many設置:爲什麼Rails沒有自動創建連接表條目?

class Tag < ActiveRecord::Base 
    has_many :profile_tags 
    has_many :profiles, :through => :profile_tags 
end 

class ProfileTags < ActiveRecord::Base 
    belongs_to :profile 
    belongs_to :tag 
end 

class Profile < ActiveRecord::Base 
    has_many :profile_tags 
    has_many :tags, :through => :profile_tags 
end 

從我的觀點,我接受了一組標籤(只是字符串),和我遍歷他們在我的控制,並呼籲Tag.create(.. ),並將它們推入一個數組中。這一切工作正常。

所以我得到一個地步,我有標籤的對象(標籤),它分別由調用返回創建數組和可變@profile這是做Profile.new

我想創建要做到:@profile.tags = tags

這樣做會導致上線這個錯誤,我嘗試分配:

uninitialized constant Profile::ProfileTag 

Rails的行事就像我需要手動創建和分配連接表關聯,即使在這裏http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association它指出,當你做這樣的任務時,會創建新的關聯,如果有些關閉,它們將被刪除。

任何想法,我可能做錯了嗎?

回答

4

Rails假定模型類以單數形式命名,即類ProfileTags應該被稱爲ProfileTag

根據所Rails的您正在使用,可能是最簡單的方式來解決,這是對3

或者重新創建Rails中使用Rails的2.X script/destroyscript/generaterails destroyrails generate的模型版本,通過將:class_name => 'ProfileTags'添加到has_many聲明中來手動指定類名稱也可以工作。