我有两个表与多对多的关系,我使用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".
我是新手,我正在使用cancan + devise为我的用户身份验证.但是,我不确定建立典型用户HABTM角色关系意味着什么,我也不了解HABTM关系是什么.
任何人都可以解释得很好或者指向一个好的教程或例子吗?
ruby-on-rails relational-database has-and-belongs-to-many devise cancan