如何写这个:
has_many :sales, foreign_key: :buyer_id, dependent: :destroy
has_many :purchased_books, class_name: 'Book', through: :sales, source: :book
这样:
has_many :purchases, class_name: 'Sale', foreign_key: :buyer_id, dependent: :destroy
has_many :purchased_books, class_name: 'Book', through: :sales, source: :book
目前它给我以下错误:
Could not find the association :sales in model User (ActiveRecord::HasManyThroughAssociationNotFoundError)
编写has_many:当foreign_key :: buyer_id时,销售在语法上是不正确的。
答案 0 :(得分:1)
:through键必须引用已定义的关联。
has_many :purchases, class_name: 'Sale', foreign_key: :buyer_id, dependent: :destroy
has_many :purchased_books, class_name: 'Book', through: :purchases, source: :book