0

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?

Abdulaziz
  • 2,201
  • 1
  • 21
  • 35

2 Answers2

1

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

Community
  • 1
  • 1
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51
0

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

Rokibul Hasan
  • 4,078
  • 2
  • 19
  • 30