Need help with ransack?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

5.0K Stars 742 Forks MIT License 1.7K Commits 88 Opened issues


Object-based searching.

Services available


Need anything else?

Contributors list


Build Status Gem Version Code Climate Backers on Open Collective Sponsors on Open Collective

Ransack enables the creation of both simple and advanced search forms for your Ruby on Rails application (demo source code here). If you're looking for something that simplifies query generation at the model or controller layer, you're probably not looking for Ransack.

Getting started

Ransack is supported for Rails 6.1, 6.0, 5.2 on Ruby 2.6.6 and later.

In your Gemfile, for the last officially released gem:

gem 'ransack'

If you would like to use the latest updates (recommended), use the

gem 'ransack', github: 'activerecord-hackery/ransack'

Issues tracker

  • Before filing an issue, please read the Contributing Guide.
  • File an issue if a bug is caused by Ransack, is new (has not already been reported), and can be reproduced from the information you provide.
  • Contributions are welcome, but please do not add "+1" comments to issues or pull requests :smiley:
  • Please do not use the issue tracker for personal support requests. Stack Overflow is a better place for that where a wider community can help you!


Ransack can be used in one of two modes, simple or advanced. For searching/filtering not requiring complex boolean logic, Ransack's simple mode should meet your needs.

If you're coming from MetaSearch (Ransack's predecessor), refer to the Updating From MetaSearch section

Simple Mode

In your controller

def index
  @q = Person.ransack(params[:q])
  @people = @q.result(distinct: true)

or without

distinct: true
, for sorting on an associated table's columns (in this example, with preloading each Person's Articles and pagination):
def index
  @q = Person.ransack(params[:q])
  @people = @q.result.includes(:articles).page(params[:page])

or use to_a.uniq to remove duplicates (can also be done in the view):

@people = @q.result.includes(:articles).page(params[:page]).to_a.uniq end

Default search options

Search parameter

Ransack uses a default

param key for search params. This may be changed by setting the
option in a Ransack initializer file (typically
Ransack.configure do |c|
  # Change default search parameter key name.
  # Default key name is :q
  c.search_key = :query

String search

After version 2.4.0 when searching a string query Ransack by default strips all whitespace around the query string. This may be disabled by setting the

option in a Ransack initializer file:
Ransack.configure do |c|
  # Change whitespace stripping behaviour.
  # Default is true
  c.strip_whitespace = false

In your view

The two primary Ransack view helpers are

, which are defined in Ransack::Helpers::FormHelper.

helper replaces
for creating the view search form

Search if the name field contains...

Search if an associated articles.title starts with...

Attributes may be chained. Search multiple attributes for one value...

The argument of

has to be in this form:


means any repetition of
plus the name of the attribute.

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


answer format can be set like this:

helper creates table headers that are sortable links

Additional options can be passed after the column attribute, like a different column title or a default sort order:

You can use a block if the link markup is hard to fit into the label parameter:

  Player Name

With a polymorphic association, you may need to specify the name of the link explicitly to avoid an

uninitialized constant Model::Xxxable
error (see issue #421):

You can also sort on multiple fields by specifying an ordered array:

In the example above, clicking the link will sort by

and then
. Specifying the sort direction on a field in the array tells Ransack to always sort that particular field in the specified direction.


fields may also be specified with a hash:

This example toggles the sort directions of both fields, by default initially sorting the

field by ascending order, and the
field by descending order.

In the case that you wish to sort by some complex value, such as the result of a SQL function, you may do so using scopes. In your model, define scopes whose names line up with the name of the virtual field you wish to sort by, as so:

class Person < ActiveRecord::Base
  scope :sort_by_reverse_name_asc, lambda { order("REVERSE(name) ASC") }
  scope :sort_by_reverse_name_desc, lambda { order("REVERSE(name) DESC") }

and you can then sort by this virtual field:

The sort link order indicator arrows may be globally customized by setting a

option in an initializer file like

You can also enable a

which is displayed on all sortable fields which are not currently used in the sorting. This is disabled by default so nothing will be displayed:
Ransack.configure do |c|
  c.custom_arrows = {
    up_arrow: '',
    down_arrow: 'U+02193',
    default_arrow: ''

All sort links may be displayed without the order indicator arrows by setting

to true in the initializer file. Note that this hides the arrows even if they were customized:
Ransack.configure do |c|
  c.hide_sort_order_indicators = true

Without setting it globally, individual sort links may be displayed without the order indicator arrow by passing

hide_indicator: true
in the sort link:

helper is like a
but returns only the url

has the same API as

PostgreSQL's sort option


options can be used to determine whether nulls appear before or after non-null values in the sort ordering.

You may want to configure it like this:

Ransack.configure do |c|
  c.postgres_fields_sort_option = :nulls_first # or :nulls_last

To treat nulls as having the lowest or highest value respectively. To force nulls to always be first or last, use

Ransack.configure do |c|
  c.postgres_fields_sort_option = :nulls_always_first # or :nulls_always_last

See this feature:

Case Insensitive Sorting in PostgreSQL

In order to request PostgreSQL to do a case insensitive sort for all string columns of a model at once, Ransack can be extended by using this approach:

module RansackObject

def self.included(base) base.columns.each do |column| if column.type == :string base.ransacker, type: :string do Arel.sql("lower(#{base.table_name}.#{})") end end end end end

class UserWithManyAttributes < ActiveRecord::Base
  include RansackObject

If this approach is taken, it is advisable to add a functional index.

This was originally asked in a Ransack issue and a solution was found on Stack Overflow.

Advanced Mode

"Advanced" searches (ab)use Rails' nested attributes functionality in order to generate complex queries with nested AND/OR groupings, etc. This takes a bit more work but can generate some pretty cool search interfaces that put a lot of power in the hands of your users. A notable drawback with these searches is that the increased size of the parameter string will typically force you to use the HTTP POST method instead of GET. :(

This means you'll need to tweak your routes...

resources :people do
  collection do
    match 'search' => 'people#search', via: [:get, :post], as: :search

... and add another controller action ...

def search
  render :index

... and update your

line in the view ...

Once you've done so, you can make use of the helpers in Ransack::Helpers::FormBuilder to construct much more complex search forms, such as the one on the demo app (source code here).

Ransack #search method

Ransack will try to make the class method

available in your models, but if
has already been defined elsewhere, you can always use the default
class method. So the following are equivalent:

Users have reported issues of

name conflicts with other gems, so the
method alias will be deprecated in the next major version of Ransack (2.0). It's advisable to use the default

For now, if Ransack's

method conflicts with the name of another method named
in your code or another gem, you may resolve it either by patching the
classmethod in
to remove the line `alias :search :ransack unless base.respond
to? :search
, or
by placing the following line in your Ransack initializer file at
Ransack::Adapters::ActiveRecord::Base.class_eval('remove_method :search')


You can easily use Ransack to search for objects in


Given these associations...

class Employee < ActiveRecord::Base
  belongs_to :supervisor

has attributes first_name:string and last_name:string


class Department < ActiveRecord::Base has_many :supervisors

has attribute title:string


class Supervisor < ActiveRecord::Base belongs_to :department has_many :employees

has attribute last_name:string


... and a controller...

class SupervisorsController < ApplicationController
  def index
    @q = Supervisor.ransack(params[:q])
    @supervisors = @q.result.includes(:department, :employees)

... you might set up your form like this...


If you have trouble sorting on associations, try using an SQL string with the pluralized table (

) instead of the symbolized association (

Ransack Aliases

You can customize the attribute names for your Ransack searches by using a

. This is particularly useful for long attribute names that are necessary when querying associations or multiple columns.
class Post < ActiveRecord::Base
  belongs_to :author

Abbreviate :author_first_name_or_author_last_name to :author

ransack_alias :author, :author_first_name_or_author_last_name end

Now, rather than using

in your form, you can simply use
. This serves to produce more expressive query parameters in your URLs.

You can also use

for sorting.
class Post < ActiveRecord::Base
  belongs_to :author

Abbreviate :author_first_name to :author

ransack_alias :author, :author_first_name end

Now, you can use

instead of
in a

Note that using

would produce an invalid sql query. In those cases, Ransack ignores the sorting clause.

Search Matchers

List of all possible predicates

| Predicate | Description | Notes | | ------------- | ------------- |-------- | |

| equal | | |
| not equal | | |
| matches with
| e.g.
| |
| does not match with
| | |
| Matches any | | |
| Matches all | | |
| Does not match any | | |
| Does not match all | | |
| less than | | |
| less than or equal | | |
| greater than | | |
| greater than or equal | | |
| not null and not empty | Only compatible with string columns. Example:
col is not null AND col != ''
) | |
| is null or empty. | (SQL:
col is null OR col = ''
) | |
| is null | | |
| is not null | | |
| match any values in array | e.g.
| |
| match none of values in array | | |
| Less than any | SQL:
col < value1 OR col < value2
| |
| Less than or equal to any | | |
| Greater than any | | |
| Greater than or equal to any | | |
| Less than all | SQL:
col < value1 AND col < value2
| |
| Less than or equal to all | | |
| Greater than all | | |
| Greater than or equal to all | | |
| none of values in a set | | |
| Starts with | SQL:
col LIKE 'value%'
| |
| Does not start with | | |
| Starts with any of | | |
| Starts with all of | | |
| Does not start with any of | | |
| Does not start with all of | | |
| Ends with | SQL:
col LIKE '%value'
| |
| Does not end with | | |
| Ends with any of | | |
| Ends with all of | | |
| | | |
| | | |
| Contains value | uses
| |
| Contains any of | | |
| Contains all of | | |
| Does not contain | |
| Does not contain any of | | |
| Does not contain all of | | |
| Contains value with case insensitive | uses
| |
| Contains any of values with case insensitive | | |
| Contains all of values with case insensitive | | |
| Does not contain with case insensitive | |
| Does not contain any of values with case insensitive | | |
| Does not contain all of values with case insensitive | | |
| is true | | |
| is false | |

(See full list: and wiki)

Using Ransackers to add custom search functions via Arel

The main premise behind Ransack is to provide access to Arel predicate methods. Ransack provides special methods, called ransackers, for creating additional search functions via Arel. More information about

methods can be found here in the wiki. Feel free to contribute working
code examples to the wiki!

Problem with DISTINCT selects

If passed

distinct: true
will generate a
to avoid returning duplicate rows, even if conditions on a join would otherwise result in some. It generates the same SQL as calling
on the relation.

Please note that for many databases, a sort on an associated table's columns may result in invalid SQL with

distinct: true
-- in those cases, you will need to modify the result as needed to allow these queries to work.

For example, you could call joins and includes on the result which has the effect of adding those tables columns to the select statement, overcoming the issue, like so:

def index
  @q = Person.ransack(params[:q])
  @people = @q.result(distinct: true)

If the above doesn't help, you can also use ActiveRecord's

query to explicitly add the columns you need, which brute force's adding the columns you need that your SQL engine is complaining about, you need to make sure you give all of the columns you care about, for example:
def index
  @q = Person.ransack(params[:q])
  @people = @q.result(distinct: true)
              .select('people.*,, articles.description')

Another method to approach this when using Postgresql is to use ActiveRecords's

in combination with
instead of
distinct: true

For example: ```ruby def index @q = Person.ransack(params[:q]) @people = @q.result .group('') .includes(:articles) .page(params[:page]) end

A final way of last resort is to call `to_a.uniq` on the collection at the end
with the caveat that the de-duping is taking place in Ruby instead of in SQL,
which is potentially slower and uses more memory, and that it may display
awkwardly with pagination if the number of results is greater than the page size.

For example:

```ruby def index @q = Person.ransack(params[:q]) @people = @q.result.includes(:articles).page(params[:page]).to_a.uniq end

PG::UndefinedFunction: ERROR: could not identify an equality operator for type json

If you get the above error while using

distinct: true
that means that one of the columns that Ransack is selecting is a
column. PostgreSQL does not provide comparison operators for the
type. While it is possible to work around this, in practice it's much better to convert those to
, as recommended by the PostgreSQL documentation.

Authorization (whitelisting/blacklisting)

By default, searching and sorting are authorized on any column of your model and no class methods/scopes are whitelisted.

Ransack adds four methods to

that you can redefine as class methods in your models to apply selective authorization:

Here is how these four methods are implemented in Ransack:

  # `ransackable_attributes` by default returns all column names
  # and any defined ransackers as an array of strings.
  # For overriding with a whitelist array of strings.
  def ransackable_attributes(auth_object = nil)
    column_names + _ransackers.keys

ransackable_associations by default returns the names

of all associations as an array of strings.

For overriding with a whitelist array of strings.

def ransackable_associations(auth_object = nil) { |a| } end

ransortable_attributes by default returns the names

of all attributes available for sorting as an array of strings.

For overriding with a whitelist array of strings.

def ransortable_attributes(auth_object = nil) ransackable_attributes(auth_object) end

ransackable_scopes by default returns an empty array

i.e. no class methods/scopes are authorized.

For overriding with a whitelist array of symbols.

def ransackable_scopes(auth_object = nil) [] end

Any values not returned from these methods will be ignored by Ransack, i.e. they are not authorized.

All four methods can receive a single optional parameter,

. When you call the search or ransack method on your model, you can provide a value for an
key in the options hash which can be used by your own overridden methods.

Here is an example that puts all this together, adapted from this blog post by Ernie Miller. In an

model, add the following
class method (preferably private):
class Article < ActiveRecord::Base
  def self.ransackable_attributes(auth_object = nil)
    if auth_object == :admin
      # whitelist all attributes for admin
      # whitelist only the title and body attributes for other users
      super & %w(title body)

private_class_method :ransackable_attributes end

Here is example code for the

class ArticlesController < ApplicationController
  def index
    @q = Article.ransack(params[:q], auth_object: set_ransack_auth_object)
    @articles = @q.result


def set_ransack_auth_object current_user.admin? ? :admin : nil end end

Trying it out in

rails console
> Article
=> Article(id: integer, person_id: integer, title: string, body: text)

> Article.ransackable_attributes => ["title", "body"]

> Article.ransackable_attributes(:admin) => ["id", "person_id", "title", "body"]

> Article.ransack(id_eq: 1).result.to_sql => SELECT "articles".* FROM "articles" # Note that search param was ignored!

> Article.ransack({ id_eq: 1 }, { auth_object: nil }).result.to_sql => SELECT "articles".* FROM "articles" # Search param still ignored!

> Article.ransack({ id_eq: 1 }, { auth_object: :admin }).result.to_sql => SELECT "articles".* FROM "articles" WHERE "articles"."id" = 1

That's it! Now you know how to whitelist/blacklist various elements in Ransack.

Handling unknown predicates or attributes

By default, Ransack will ignore any unknown predicates or attributes:

Article.ransack(unknown_attr_eq: 'Ernie').result.to_sql
=> SELECT "articles".* FROM "articles"

Ransack may be configured to raise an error if passed an unknown predicate or attributes, by setting the

option to
in your Ransack initializer file at
Ransack.configure do |c|
  # Raise errors if a query contains an unknown predicate or attribute.
  # Default is true (do not raise error on unknown conditions).
  c.ignore_unknown_conditions = false
Article.ransack(unknown_attr_eq: 'Ernie')
# ArgumentError (Invalid search term unknown_attr_eq)

As an alternative to setting a global configuration option, the

class method also raises an error if passed an unknown condition:
Article.ransack!(unknown_attr_eq: 'Ernie')
# ArgumentError: Invalid search term unknown_attr_eq

This is equivalent to the

configuration option, except it may be applied on a case-by-case basis.

Using Scopes/Class Methods

Continuing on from the preceding section, searching by scopes requires defining a whitelist of

on the model class. The whitelist should be an array of symbols. By default, all class methods (e.g. scopes) are ignored. Scopes will be applied for matching
values, or for given values if the scope accepts a value:
class Employee < ActiveRecord::Base
  scope :activated, ->(boolean = true) { where(active: boolean) }
  scope :salary_gt, ->(amount) { where('salary > ?', amount) }

Scopes are just syntactical sugar for class methods, which may also be used:

def self.hired_since(date) where('start_date >= ?', date) end

def self.ransackable_scopes(auth_object = nil) if auth_object.try(:admin?) # allow admin users access to all three methods %i(activated hired_since salary_gt) else # allow other users to search on activated and hired_since only %i(activated hired_since) end end end

Employee.ransack({ activated: true, hired_since: '2013-01-01' })

Employee.ransack({ salary_gt: 100_000 }, { auth_object: current_user })

In Rails 3 and 4, if the

value is being passed via url params or some other mechanism that will convert it to a string, the true value may not be passed to the ransackable scope unless you wrap it in an array (i.e.
activated: ['true']
). Ransack will take care of changing 'true' into a boolean. This is currently resolved in Rails 5 :smiley:

However, perhaps you have

user_id: [1]
and you do not want Ransack to convert 1 into a boolean. (Values sanitized to booleans can be found in the constants.rb). To turn this off globally, and handle type conversions yourself, set
to false in an initializer file like config/initializers/ransack.rb:
Ransack.configure do |c|
  c.sanitize_custom_scope_booleans = false

To turn this off on a per-scope basis Ransack adds the following method to

that you can redefine to selectively override sanitization:


Add the scope you wish to bypass this behavior to ransackablescopesskipsanitizeargs:

def self.ransackable_scopes_skip_sanitize_args

Scopes are a recent addition to Ransack and currently have a few caveats: First, a scope involving child associations needs to be defined in the parent table model, not in the child model. Second, scopes with an array as an argument are not easily usable yet, because the array currently needs to be wrapped in an array to function (see this issue), which is not compatible with Ransack form helpers. For this use case, it may be better for now to use ransackers instead, where feasible. Pull requests with solutions and tests are welcome!

Grouping queries by OR instead of AND

The default

grouping can be changed to
by adding
m: 'or'
to the query hash.

You can easily try it in your controller code by changing

in the
action to
params[:q].try(:merge, m: 'or')
as follows:
def index
  @q = Artist.ransack(params[:q].try(:merge, m: 'or'))
  @artists = @q.result

Normally, if you wanted users to be able to toggle between

query grouping, you would probably set up your search form so that
was in the URL params hash, but here we assigned
manually just to try it out quickly.

Alternatively, trying it in the Rails console:

artists = Artist.ransack(name_cont: 'foo', style_cont: 'bar', m: 'or')
=> Ransack::Search,
  ], combinator: or>>

artists.result.to_sql => "SELECT "artists".* FROM "artists" WHERE (("artists"."name" ILIKE '%foo%' OR "artists"."style" ILIKE '%bar%'))"

The combinator becomes

instead of the default
, and the SQL query becomes
instead of

This works with associations as well. Imagine an Artist model that has many Memberships, and many Musicians through Memberships:

artists = Artist.ransack(name_cont: 'foo', musicians_email_cont: 'bar', m: 'or')
=> Ransack::Search,
  ], combinator: or>>

artists.result.to_sql => "SELECT "artists".* FROM "artists" LEFT OUTER JOIN "memberships" ON "memberships"."artist_id" = "artists"."id" LEFT OUTER JOIN "musicians" ON "musicians"."id" = "memberships"."musician_id" WHERE (("artists"."name" ILIKE '%foo%' OR "musicians"."email" ILIKE '%bar%'))"

Using SimpleForm

If you would like to combine the Ransack and SimpleForm form builders, set the

environment variable before Rails boots up, e.g. in
require 'rails/all'
as shown below (and add
gem 'simple_form'
in your Gemfile).
require File.expand_path('../boot', __FILE__)
ENV['RANSACK_FORM_BUILDER'] = '::SimpleForm::FormBuilder'
require 'rails/all'


Ransack translation files are available in Ransack::Locale. You may also be interested in one of the many translations for Ransack available at

Predicate and attribute translations in forms may be specified as follows (see the translation files in Ransack::Locale for more examples):


    asc: ascending
    desc: descending
      cont: contains
      not_cont: not contains
      start: starts with
      end: ends with
      gt: greater than
      lt: less than
      person: Passanger
        name: Full Name
        title: Article Title
        body: Main Content

Attribute names may also be changed globally, or under

      model_field1: field name1
      model_field2: field name2
        title: AR Namespaced Title
        title: Old Ransack Namespaced Title

Updating From MetaSearch

Ransack works much like MetaSearch, for those of you who are familiar with it, and requires very little setup effort.

If you're coming from MetaSearch, things to note:

  1. The default param key for search params is now

    , instead of
    . This is primarily to shorten query strings, though advanced queries (below) will still run afoul of URL length limits in most browsers and require a switch to HTTP POST requests. This key is configurable via setting the
    option in your Ransack intitializer file.
  2. form_for
    is now
    , and validates that a Ransack::Search object is passed to it.
  3. Common ActiveRecord::Relation methods are no longer delegated by the search object. Instead, you will get your search results (an ActiveRecord::Relation in the case of the ActiveRecord adapter) via a call to



Mongoid support has been moved to its own gem at ransack-mongoid. Ransack works with Mongoid in the same way as Active Record, except that with Mongoid, associations are not currently supported. Demo source code may be found here. A

method called on a
search returns a
  @q = Person.ransack(params[:q])
  @people = @q.result # => Mongoid::Criteria

or you can add more Mongoid queries

@people = -1).limit(10)

NOTE: Ransack currently works with either Active Record or Mongoid, but not both in the same application. If both are present, Ransack will default to Active Record only. The logic is contained in

should you need to override it.

Semantic Versioning

Ransack attempts to follow semantic versioning in the format of

, where:

stands for a major version (new features that are not backward-compatible).

stands for a minor version (new features that are backward-compatible).

stands for a patch (bug fixes).

In other words:



To support the project:

  • Consider supporting via Open Collective
  • Use Ransack in your apps, and let us know if you encounter anything that's broken or missing. A failing spec to demonstrate the issue is awesome. A pull request with passing tests is even better!
  • Before filing an issue or pull request, be sure to read and follow the Contributing Guide.
  • Please use Stack Overflow or other sites for questions or discussion not directly related to bug reports, pull requests, or documentation improvements.
  • Spread the word on Twitter, Facebook, and elsewhere if Ransack's been useful to you. The more people who are using the project, the quicker we can find and fix bugs!


This project exists thanks to all the people who contribute.

Ransack is a rewrite of MetaSearch created by Ernie Miller and developed/maintained by:

While it supports many of the same features as MetaSearch, its underlying implementation differs greatly from MetaSearch, and backwards compatibility is not a design goal.


Thank you to all our backers! 🙏 [Become a backer]


Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.