Rajeev Kannav Sharma

Posts About

Object-based searching rails Active-Record

14 May 2016


We have listing of all Users and other data list at our admin panels per application. A basic Search functionality was required with less efforts and adjustable quickly.


In your Gemfile, for the last officially released gem: gem 'ransack'

In your controller
def index
  @q = Person.ransack(params[:q])
  @people = @q.result(distinct: true)
In your view
<%= search_form_for @q do |f| %>

  # Search if the name field contains...
  <%= f.label :name_cont %>
  <%= f.search_field :name_cont %>

  # Search if an associated articles.title starts with...
  <%= f.label :articles_title_start %>
  <%= f.search_field :articles_title_start %>

  # Attributes may be chained. Search multiple attributes for one value...
  <%= f.label :name_or_description_or_email_or_articles_title_cont %>
  <%= f.search_field :name_or_description_or_email_or_articles_title_cont %>

  <%= f.submit %>
<% end %>

cont (contains) and start (starts with) are just two of the available search predicates. See Constants for a full list and the wiki for more information.

<%= sort_link(@q, :name) %>

And if you get stuck… Ask Here

email me rajeevsharma86@gmail.com

Tweet to me at @rajeevkannav.