Search code examples
ruby-on-railsransack

Ransack return records with boolean attribute both true and false with checkbox


I am using Ransack to create a search form on a model called Car. I have several boolean attributes on Car and I have included checkboxes in my search form for each one of them, for example:

<%= f.check_box :car_spec_anti_lock_brakes_true %>
<%= f.label :car_spec_anti_lock_brakes_true, "ABS" %>

When this checkbox is checked, the search results include all records where car_spec_anti_lock_brakes is true. When it is left unchecked, the results only return records where car_spec_anti_lock_brakes is false. How can I implement the search form so that when the checkbox is left unchecked all records where car_spec_anti_lock_brakes is either true or false are returned. So when the checkbox is checked return all records that have the attribute, but when it is unchecked return all records, independent of whether the attribute is true or false.


Solution

  • I solved this by editing the params hash that is passed to the Car.search method. I remove parameters from the hash if the checkbox is left unchecked. So if I have the following checkboxes:

    <%= f.check_box :car_spec_anti_lock_brakes_true %>
    <%= f.label :car_spec_anti_lock_brakes_true, "ABS" %>
    
    <%= f.check_box :car_spec_traction_control_true %>
    <%= f.label :car_spec_traction_control_true, "Traction control" %>
    
    <%= f.check_box :car_spec_rims_true %>
    <%= f.label :car_spec_rims_true, "Rims" %>
    

    The params[:q] hash will have the keys :car_spec_anti_lock_brakes_true, :car_spec_traction_control_true, :car_spec_rims_true. When a checkbox is left unchecked the corresponding key will have a value of 0 in the params[:q] hash when it is passed into the search. The solution is to remove the keys that have 0 values from the params[:q] hash before they are passed into the search:

    if params[:q]
        @params = params[:q]
        @params.delete(:car_spec_anti_lock_brakes_true) if @params[:car_spec_anti_lock_brakes_true] = '0'
        @params.delete(:car_spec_traction_control_true) if @params[:car_spec_traction_control_true] = '0'
        @params.delete(:car_spec_anti_rims_true) if @params[:car_spec_rims_true] = '0'
    else
        @params = []
    end
    
    @search = Car.search(@params)
    @cars = @search.result