mysql - rails : has_many through with multiple foreign keys?

标签 mysql ruby-on-rails

我有 2 个表和一个联接表:

模型1:

class Book < ActiveRecord::Base
  has_many :book_people
  has_many :illustrators, through: :book_people, class_name: 'ComaPerson', foreign_key: 'illustrator_id'
  has_many :authors, through: :book_people, class_name: 'ComaPerson', foreign_key: 'author_id'

连接表:

class BookPerson < ActiveRecord::Base
  belongs_to :book
  belongs_to :illustrator, class_name: 'ComaPerson', foreign_key: 'illustrator_id'
  belongs_to :author, class_name: 'ComaPerson', foreign_key: 'author_id'

模型 2(给我带来问题的模型):

class ComaPerson < ActiveRecord::Base
  has_many :book_people #<-- not working
  has_many :books, :through => :book_people

我的测试失败,因为它表明 BookPerson 模型没有 coma_person_id 列:

Failures:

  1) ComaPerson should have many book_people
     Failure/Error: it { should have_many(:book_people) }
       Expected ComaPerson to have a has_many association called book_people (BookPerson does not have a coma_person_id foreign key.)
     # ./spec/models/coma_person_spec.rb:5:in `block (2 levels) in <top (required)>'

由于ComaPerson既可以是插画家,也可以是作者,所以我在连接表中使用了illustrator_idauthor_id,因此连接表有三列:book_id、illustrator_id和作者 ID'。这是否意味着我必须向联接表添加 coma_person_id 列才能使其工作?

最佳答案

我想我已经明白了。因此,您必须屏蔽 has_many :join_table_name 并将它们分成两部分,每个foreign_key 一个,同时指定模型名称和外键是什么。

class ComaPerson < ActiveRecord::Base
  has_many :authored_books_people, class_name: 'BookPerson', foreign_key: 'author_id'
  has_many :illustrated_book_people, class_name: 'BookPerson', foreign_key: 'illustrator_id'
  has_many :authored_books, through: :authored_books_people, primary_key: 'author_id', source: :book
  has_many :illustrated_books, through: :illustrated_book_people, primary_key: 'illustrator_id', source: :book

关于mysql - rails : has_many through with multiple foreign keys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19983708/

相关文章:

ruby-on-rails - 突然开始收到 "Could Not Run The ` 识别命令。请安装 ImageMagick。”

ruby-on-rails - 在 Rails 中使用 titleize 作为首字母缩略词

ruby-on-rails - 如何使用 Heroku 阻止推荐垃圾邮件

mysql - Forum Schema : should the "Topics" table countain topic_starter_Id? 还是冗余信息?

mysql - 如何在 mySQL 中将表与 null 合并

ruby-on-rails - 在 Rails 中将 View 渲染为文本

ruby-on-rails - 当 FK 关联对象不是 AR 关系时,可以在 FactoryBot 定义中使用随机 FK ID 吗?

mysql - 我无法锁定表格,之前它正在工作

mysql - 按订单存储产品 - 下订单后产品将被删除

php - 带有 nginx、mysql、php7 和 slimphp 的 Dockerfile