Ransack: Search with Multiple Checkboxes (Rails)

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:

class Zoo < ActiveRecord::Base
  has_many :animals

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

Next, the controller, which is pretty much out-of-the-box from the Ransack documentation:

class ZoosController < ApplicationController
  def search # or index
    @search = Zoo.search(params[:q])
    @zoos = @search.result(distinct: true)

And finally, the magic is really in the view:

<%= 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 %>

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.


4 Comments on “Ransack: Search with Multiple Checkboxes (Rails)”

  1. davity says:

    Thank you! Works like a charm.
    Also, for a clickable label you can do

  2. Marina says:

    You are missing a parentheses on line 4 in the view.

  3. Johannes says:

    I think you forgot the closing paren for: check_box_tag(

    Other then that thanks alot, works great.

  4. josh says:

    Thanks, I have updated to correct the missing parentheses.