小编Kei*_*ith的帖子

创建没有主键的连接表

我有两个表与多对多的关系,我使用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
Run Code Online (Sandbox Code Playgroud)

我还定义了表示连接表的类

class BarFoo < ActiveRecord::Base
  ...
  belongs_to :foo
  belongs_to :bar
  ...
end
Run Code Online (Sandbox Code Playgroud)

当我运行rake db:seed时出现以下错误:

Primary key is not allowed in a has_and_belongs_to_many join table (bar_foo)
Run Code Online (Sandbox Code Playgroud)

如果我编辑数据库并从bar_foo表中删除主键字段(ID),然后重新运行rake db:seed一切都按预期工作.

鉴于上述情况,在没有主键的rails中创建连接表的首选方法是什么?

我也尝试使用"has_many:bars,:through =>:foo",反之亦然,但得到的错误信息类似于"未定义的方法'klass'为nil:NilClass".

join ruby-on-rails primary-key has-and-belongs-to-many

12
推荐指数
3
解决办法
2万
查看次数