【发布时间】:2011-04-29 05:06:15
【问题描述】:
我有两个具有多对多关系的表,我使用 has_and_belongs_to_many 来定义关联。
class Foo < ActiveRecord::Base
...
has_and_belongs_to_many :bar
...
end
class Bar < ActiveRecord::Base
...
has_and_belongs_to_many :foo
...
end
我还定义了代表连接表的类
class BarFoo < ActiveRecord::Base
...
belongs_to :foo
belongs_to :bar
...
end
当我运行 rake db:seed 时出现以下错误:
Primary key is not allowed in a has_and_belongs_to_many join table (bar_foo)
如果我编辑数据库并从 bar_foo 表中删除主键字段 (ID),然后重新运行 rake db:seed,一切都会按预期工作。
鉴于上述情况,在没有主键的 Rails 中创建连接表的首选方法是什么?
我也尝试使用“has_many :bars, :through => :foo”,反之亦然,但收到类似“undefined method 'klass' for nil:NilClass”的错误消息。
【问题讨论】:
标签: ruby-on-rails join primary-key has-and-belongs-to-many