簡體   English   中英

Rails:has_many通過多個外鍵?

[英]Rails: has_many through with multiple foreign keys?

我有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列才能使其工作?

我想我明白了。 因此,您必須屏蔽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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM