0

I'm using has_scope gem and I want to create filtering with two params — it may be one param or two same time.

Mymodel (Product):

scope :brand, proc { |brand| joins(:product_values).where('product_values.value_id' => brand) }
scope :zamena, proc { |zamena| joins(:product_values).where('product_values.value_id' => zamena) }

Index action of controller:

 @products = apply_scopes(Product).all

It works, but only by one :(

/products?brand=12 - Ok
/products?zamena=24 - Ok
/products?brand=12&zamena=24 - Fail (sorted only by 'zamena', not by both params)

2nd. variant (not works too) In my controller:

query = Product.scoped
query = query.brand(params[:brand]) if params[:brand]
query = query.zamena(params[:zamena]) if params[:zamena]
@products = query.all

Works by one, but not both (0 results).

infused
  • 24,000
  • 13
  • 68
  • 78
Oleg Pasko
  • 2,831
  • 5
  • 35
  • 44
  • What is your expected behavior? Both of your scopes are exactly the same. You're asking for all of the products where `product_values.value_id == 12` AND `product_values.value_id == 24`. You can't expect the same attribute to have two separate values. – Nick Colgan Dec 12 '12 at 21:27
  • Exactly. I want to get products with value_id == 12 and value_id == 24 same time (product has_many values throught product_values). Thanks. I understand problem, but not solved it yet :) – Oleg Pasko Dec 12 '12 at 21:31
  • have a look here: http://stackoverflow.com/questions/8314282/rails-3-multiple-parameter-filtering-using-scopes – Roger Dec 13 '12 at 01:45
  • Rogier, thanks, but not worked for me. Maybe "scoped" method differ from 3.1 rails version, or something else. – Oleg Pasko Dec 13 '12 at 19:10

1 Answers1

-1

My answer. Maybe not elegant, but works nice.

  fcount = 0
  fcount += 1 if params[:brand]
  fcount += 1 if params[:zamena]

  prods = []
  if params[:brand]
    Product.all.each do |p|
      prods << p if p.product_values.where(value_id: params[:brand]).count > 0
    end
  end
  if params[:zamena]
    Product.all.each do |p|
      prods << p if p.product_values.where(value_id: params[:zamena]).count > 0
    end
  end

  @products = prods.select{|item| prods.count(item) == fcount}.uniq

No scopes needed. You can use a lot of filters using this way.

Oleg Pasko
  • 2,831
  • 5
  • 35
  • 44