Rails - 如何使用具有复合主键的has_and_belongs_to_many关联

8

我正在使用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
1个回答

8
根据Ruby on Rails风格指南

优先使用has_many :through而不是has_and_belongs_to_many。使用has_many :through可在关联模型上添加其他属性和验证。

这将解决您的问题:您将只拥有has_many和belongs_to关系,没有HABTM ;) 在您的情况下:
class Book < ActiveRecord::Base
  self.primary_keys = :title, :author
  has_many :book_genre_relations
  has_many :genres, through: :book_genre_relations
end

class Genre < ActiveRecord::Base
  has_many :book_genre_relations
  has_many :books, through: :book_genre_relations
end

class BookGenreRelation < ActiveRecord::Base # Sorry but couldn't find a better name...
  belongs_to :book
  belongs_to :genre
end

你可能需要更改外键的错字,我不熟悉组合主键。


很棒,它可以工作了。我必须稍微修改一下选项: 对于Genre,使用has_many:book_genre_relations,没有特定的外键(默认值很好) 对于BookGenreRelation,同样使用belongs_to:genre,默认的外键就可以。谢谢! - Vall3y

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接