I'm trying to create a records filtering system using ActiveRecord scopes but i am stuck at the point where you have two filters of the same model. I am trying to filter products with brand_id: 1
and brand_id:2
My Product
model with the brand
scope defined looks like this:
class Product < ActiveRecord::Base
belongs_to :brand
scope :brand, lambda{|brand| where('brand_id = ?', brand )}
end
I am trying to filter the products on my categories/show
view and the CategoriesController
looks like this:
class CategoriesController < ApplicationController
has_scope :brand
def show
@category = Category.find(params[:id])
@products_by_category = apply_scopes(Product).where(category_id: @category).load
@brands = @category.brands
end
end
The categories/show
view looks like this:
<% @products_by_category.each do |product| %>
<h2><%= product.name %></h2>
<% end %>
i am using this form to do the filtering:
<%= form_tag @category_path, method: get do %>
<% @brands.each do |brand| %>
<span class="filter_name"><%= brand.name%>:</span>
<span> <%= check_box_tag :brand, brand.id, false,
class: 'filter_check_box' %> </span>
<% end %>
<%=submit_tag 'filter'%>
<% end %>
The problem is when i select more than one brand in the check_boxes, it filters the products with only the first parameter;
for example if i filter with brands with :id 1
and :id 2
and submits the form,
it the request url looks like this: http://localhost:3000/categories/1?&brand=1&brand=4
and the queried array is only filtered with brand=1
. I would like the results to be filtered by both parameters. Is the resulting url even correct or should it be:
http://localhost:3000/categories/1?&brand=1,4
?