我有 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_id
和author_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/