2015-09-10 34 views
0

我想通過模型的實例變量來確定模型的has_many關係。如何在has_many關聯範圍內訪問模型的實例變量?

我有這樣一個模型:

class Category < ActiveRecord::Base 
    has_many :products, -> { where(product_type: @product_type) } 
    attr_accessor :product_type 

然後我會做這樣的事情:

category = Category.find(id) 
category.product_type = 'type' 
category.products # expected output: SELECT * FROM `products` ... WHERE `product_type` = 'type' 

在片段給,問題是,範圍正在試圖獲得@product_typeActiveRecord::Relation而不是模型本身。

如何使其按照預期工作?

回答