Search code examples
ruby-on-railsscopehas-scope

Rails: multiple params (filter) with has_scope


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).


Solution

  • 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.