Multiple checkboxes filtering using filterrific

821 views Asked by At

I have 4 checkboxes using the same scope. It's used for filtering the house with certain number of bedrooms. The last checkbox stand for "4 and more" bedroom

<%= f.check_box(:with_bedroom_num_check, {multiple: true}, '1', nil) %>
<%= f.check_box(:with_bedroom_num_check, {multiple: true}, '2', nil) %>
<%= f.check_box(:with_bedroom_num_check, {multiple: true}, '3', nil) %>
<%= f.check_box(:with_bedroom_num_check, {multiple: true}, 'more', nil) %>

When I check/uncheck these checkboxes, the parameter array passed to the scope change.

For example

x o o o

When the first box is checked, the array is [1]. It should show houses with 1 bedroom.

x x x x

The array is [1, 2, 3, more]. It should show all houses.

x x o o

The array is [1, 2]. It should show houses with 1 or 2 bedrooms.

x o o x

The array is [1, more]. It should show houses with 1, 4 or more bedrooms.

Currently, my scope is:

scope :with_bedroom_num_check, lambda { |flag|
    where(bedroom:[flag])
}

It only works with 1-3 bedrooms. How could I show all houses with 4 or more bedrooms when the last checkbox is checked?

1

There are 1 answers

1
rxing On BEST ANSWER

Try below in your scope. Before that use '4' instead of 'more' as the value of your last checkbox.

   ([1, 2, 3, 4] - flag).inject(all) do |x, y|
      if y == 4
        x.where.not("with_bedroom_num_check >= ?", y)
      else
        x.where.not(with_bedroom_num_check: y)
      end
    end