Ransack: Search with Multiple Checkboxes (Rails)

Posted by jkahn on March 08, 2014 · 1 min read

I've been using the outstanding Ransack gem to enable search for a recent project. Ransack provides a tremendous amount of flexibility in a straightforward manner, but it took me a bit to understand how to search a single field across multiple values selected via checkboxes. My approach follows.

(Note that the field I was searching contained a serialized array of data, not to make life more difficult)

To start, a simplified model:
[code language="ruby"]
class Zoo < ActiveRecord::Base
has_many :animals
end

class Animal < ActiveRecord::Base
belongs_to :zoo # we'll assume an animal can only belong to one zoo
validates_presence_of :name
end
[/code]

Next, the controller, which is pretty much out-of-the-box from the Ransack documentation:
[code language="ruby"]
class ZoosController < ApplicationController
def search # or index
@search = Zoo.search(params[:q])
@zoos = @search.result(distinct: true)
end
end
[/code]

And finally, the magic is really in the view:
[code language="html"]
<%= search_form_for @search, url: search_zoos_url do |f| %>
<% Animal.all.uniq.each do |animal| %>
# the check_box helper will not work as effectively here
<%= check_box_tag('q[animals_name_cont_any][]', animal.name) %>
<%= animal.name %>
<% end %>
<%= f.submit "Search" %>
<% end %>
[/code]

The key is the name of the check box field. We are passing an array and also using Ransack's cont_any predicate, which searches for any records whose name field contains one of the selected names.