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