我正在使用Dr.Nic的Rails复合主键插件(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
编辑:我还使用Genre模型上的:association_foreign_key
选项使其工作。
class Genre < ActiveRecord::Base
has_and_belongs_to_many :books, association_foreign_key: [:title, :author]
end
has_many:book_genre_relations
,没有特定的外键(默认值很好) 对于BookGenreRelation,同样使用belongs_to:genre
,默认的外键就可以。谢谢! - Vall3y