2010-09-11 41 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声明中来手动指定类名称也可以工作。