0

我有 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 既可以是插画家也可以是作者,我在 join 表中使用了illustrator_idand author_id,所以 join 表有 'book_id、illustrator_id 和 author_id' 三列。这是否意味着我必须在连接表中添加一个 coma_person_id 列才能使其工作?

4

1 回答 1

2

我想我想通了。因此,您必须将它们屏蔽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
于 2013-11-14T17:33:55.970 回答