我有一个简单的 has_many 通过关系设置:
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
在我看来,我正在接受一组标签(只是字符串),并在我的 Controller 中迭代它们并在每个标签上调用 Tag.create( ... ),并将它们插入一个数组。这一切都很好。
所以我得到了一个点,我有一个 Tag 对象(标签)数组,每个对象都由创建调用返回,还有变量@profile,它是通过执行 Profile.new 创建的
我想这样做:@profile.tags = tags
这样做会在我尝试赋值的那一行导致这个错误:
uninitialized constant Profile::ProfileTag
Rails 就像我需要手动创建和分配连接表关联一样,即使这里是 http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association它指出,当您执行这样的任务时,将创建新的关联,如果一些关联消失,它们将被删除。
知道我在这里做错了什么吗?
最佳答案
Rails 假定模型类以单数形式命名,即类 ProfileTags
应称为 ProfileTag
。
根据您使用的 Rails 版本,解决此问题的最简单方法可能是在 Rails 中使用 script/destroy
和 script/generate
重新创建模型2.x 或 Rails 3 中的 rails destroy
和 rails generate
。
或者,通过将 :class_name => 'ProfileTags'
添加到 has_many
声明来手动指定类名也应该有效。
关于ruby-on-rails - 为什么 Rails 不自动创建连接表条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3692183/