Reputation: 389
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.
Upvotes: 4
Views: 3275
Reputation: 143
I solved by editing view file.
Your code generates hidden form that provides false param.
<%= f.check_box :car_spec_anti_lock_brakes_true %>
#generated html code
<input type="hidden" value="0" name="q[car_spec_anti_lock_brakes_true]"></input>
<input id="q_car_spec_anti_lock_brakes_true" type="checkbox" value="1" name="q[car_spec_anti_lock_brakes_true]"></input>
So, I removed hidden form.
<%= f.check_box :car_spec_anti_lock_brakes_true, include_hidden: false %>
#generated html code
<input id="q_car_spec_anti_lock_brakes_true" name="q[car_spec_anti_lock_brakes_true]" value="1" type="checkbox"></input>
When the checkbox is left unchecked all records where car_spec_anti_lock_brakes
is either true or false are returned.
Upvotes: 13
Reputation: 389
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
Upvotes: 0