Rails:has_many通过多个外键?

时间:2013-11-14 16:58:21

标签: 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和author_id'。这是否意味着我必须在连接表中添加coma_person_id列才能使其正常工作?

1 个答案:

答案 0 :(得分: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