问题
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
回答1:
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
回答2:
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])
来源:https://stackoverflow.com/questions/19829848/rails-ransack-how-to-search-multiple-values