我有兩個表具有多對多關係,我使用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
當我運行耙分貝:種子我得到以下錯誤:
Primary key is not allowed in a has_and_belongs_to_many join table (bar_foo)
如果我編輯數據庫並從bar_foo表中刪除主鍵字段(ID),然後重新運行rake數據庫:種子一切正常。
鑑於上述情況,在沒有主鍵的rails中創建連接表的首選方法是什麼?
我也嘗試使用「has_many:bars,:through =>:foo」,反之亦然,但得到了類似「未定義的方法'klass'for nil:NilClass」的錯誤消息。
馬特,謝謝你的回覆。我對RoR比較陌生,所以創建沒有相應模型文件的表的首選方法是什麼?這只是通過生成一個遷移文件並使用create_table來定義具有兩個屬性bar_id和foo_id的表來完成的? – Keith 2010-10-22 15:10:58
下面是一個很好的答案:[我需要手動創建HABTM連接表的遷移嗎?](http://stackoverflow.com/questions/564306/do-i-need-to-manually-create -a遷移-FOR-A-HABTM聯接表) – Matt 2010-10-22 15:27:09