Rails Ransack - How to search multiple values

前提是你 提交于 2019-12-14 02:32:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!