如何通过关系使用has_many的命名关联?

时间:2015-03-20 05:22:40

标签: ruby-on-rails activerecord

如何写这个:

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时,销售在语法上是不正确的。

1 个答案:

答案 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