如何将 named_association 用于 has_many_through 关系?
How to use a named_association for has_many_through relationship?
如何写:
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 :sales 在 foreign_key: :buyer_id 时语法不正确。
:through 键必须引用已定义的关联。
has_many :purchases, class_name: 'Sale', foreign_key: :buyer_id, dependent: :destroy
has_many :purchased_books, class_name: 'Book', through: :purchases, source: :book
如何写:
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 :sales 在 foreign_key: :buyer_id 时语法不正确。
:through 键必须引用已定义的关联。
has_many :purchases, class_name: 'Sale', foreign_key: :buyer_id, dependent: :destroy
has_many :purchased_books, class_name: 'Book', through: :purchases, source: :book