简体   繁体   中英

How can I access a model's instance variable within a has_many association scope?

I'm trying to scope a has_many relation of a model, by the model's instance variable.

I have a model like this:

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

Then I'd do something like this:

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

In the snippet give, the problem is that the scope is trying to get @product_type from the ActiveRecord::Relation and not the model itself.

How do I make it work as intended?

You can do the following:

has_many :products, :conditions => proc { "product_type = #{self.product_type}" }

You can check this out also: Rails has_many with dynamic conditions

What about if you pass object through the scope

has_many :products, ->(object) { where(product_type: object.product_type) }

Or Pass the product_type directly

has_many :products, ->(product_type) { where(product_type: product_type) }

Sources: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM