加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails – 如何使用has_and_belongs_to_many与

发布时间:2020-12-17 04:40:13 所属栏目:百科 来源:网络整理
导读:我正在使用Dr.Nic的复合主键(http://compositekeys. rubyforge.org/) 在示例中,他有has_many和belongs_to关系,但没有has_and_belongs_to_many 我的协会在书籍和流派之间运作良好(书籍具有标题和作者的复合素数键),但是书籍的类型试图查询连接表中不存在的列b
我正在使用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,:author]
end

编辑:我也使用它来工作:类型模型上的association_foreign_key选项

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

解决方法

根据 Ruby on Rails Style Guide:

Prefer has_many :through to has_and_belongs_to_many. Using has_many :through allows additional attributes and validations on the join model.

这将解决您的问题:您将只有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的拼写错误,我不熟悉复合主键.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读