简体   繁体   中英

Rails Ransack - How to search multiple values

Using the Ransack gem I was able to implement a search using checkboxes for certain values. However, this doesn't work with more than one checkbox. What am I missing?

View:

<%= search_form_for @search do |f| %>
  Part Time:<%= check_box_tag "q[job_type_cont]", value = "Part time" %></br>
  Full Time:<%= check_box_tag "q[job_type_cont]", value = "Full time" %></br>
  <%= f.submit "Search" %>
<% end %>

Index Action:

def index
  @search = Job.search(params[:q])
  @jobs = @search.result
 end

Your view will always send only one value in params[:q][:job_type_cont] it will be a string with either Part time or Full time For receiving multiple values, you need to change it to an array (You need to change checkbox name attribute) as follows

Part Time: <%= check_box_tag "q[job_type_cont][]", "Part time" %></br>
Full Time: <%= check_box_tag "q[job_type_cont][]", "Full time" %>

With above implementation, in controller params[:q][:job_type_cont] will be an array with selected values from the view

Kalpesh suggests

Part Time: <%= check_box_tag "q[job_type_cont][]", "Part time" %></br>
Full Time: <%= check_box_tag "q[job_type_cont][]", "Full time" %>

with

@search = Job.search(job_type_in: params[:q][:job_type_cont])
@jobs = @ search.result

which is really a roundabout way of saying:

Part Time: <%= check_box_tag "q[job_type_in][]", "Part time" %></br>
Full Time: <%= check_box_tag "q[job_type_in][]", "Full time" %>

that way there's no need for funny business in your controller:

@search = Job.search(params[:q])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM