Search code examples
ruby-on-railsruby-on-rails-3.2ransack

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

Solution

  • 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