小编Val*_*l3y的帖子

Rails - 如何使用has_and_belongs_to_many与复合主键关联

我正在使用Dr.Nic的复合主键(http://compositekeys.rubyforge.org/)

在示例中,他有has_many和belongs_to关系,但没有has_and_belongs_to_many

我的协会在书籍和流派之间运作良好(书籍具有标题和作者的复合素数键),但是书籍的类型试图查询连接表中不存在的列book_id,并引发错误.

class Book < ActiveRecord::Base
  self.primary_keys = :title, :author
  has_and_belongs_to_many :genres, foreign_key: [:title, :author]
end

class Genre < ActiveRecord::Base
  has_and_belongs_to_many :books, foreign_key: [:title, :author]
end
Run Code Online (Sandbox Code Playgroud)

编辑:我也使用:association_foreign_keyGenre模型上的选项工作

class Genre < ActiveRecord::Base
  has_and_belongs_to_many :books, association_foreign_key: [:title, :author]
end
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails

8
推荐指数
1
解决办法
2153
查看次数

标签 统计

ruby-on-rails ×1