【问题标题】:Rails - How to use has_and_belongs_to_many association with Composite Primary KeysRails - 如何使用 has_and_belongs_to_many 与复合主键的关联
【发布时间】:2012-11-30 17:59:12
【问题描述】:

我正在使用 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

编辑:我还使用流派模型上的:association_foreign_key 选项使其工作

class Genre < ActiveRecord::Base
  has_and_belongs_to_many :books, association_foreign_key: [:title, :author]
end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    根据Ruby on Rails Style Guide

    更喜欢 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
    

    您可能需要更改 foreign_key 的拼写错误,我不熟悉复合主键。

    【讨论】:

    • 酷,它有效。我不得不稍微修改一下选项:对于类型,has_many :book_genre_relations,没有特定的外键(默认是好的)对于 BookGenreRelation,belongs_to :genre,默认外键有效。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多