2011-06-06 21:32:03 -04:00
# Ransack
2014-04-24 03:14:51 -04:00
[![Build Status ](https://travis-ci.org/activerecord-hackery/ransack.svg )]
(https://travis-ci.org/activerecord-hackery/ransack)
[![Gem Version ](https://badge.fury.io/rb/ransack.svg )]
(http://badge.fury.io/rb/ransack)
Ransack is a rewrite of [MetaSearch]
(https://github.com/activerecord-hackery/meta_search)
created by [Ernie Miller ](http://twitter.com/erniemiller )
and maintained by [Ryan Bigg ](http://twitter.com/ryanbigg ),
[Jon Atack ](http://twitter.com/jonatack ) and a great group of [contributors ](https://github.com/activerecord-hackery/ransack/graphs/contributors ).
While it supports many of the same features as MetaSearch, its underlying
implementation differs greatly from MetaSearch,
2014-08-17 18:49:55 -04:00
and backwards compatibility is not a design goal.
2014-04-24 03:14:51 -04:00
Ransack enables the creation of both simple and
[advanced ](http://ransack-demo.herokuapp.com/users/advanced_search )
search forms against your application's models (demo source code
[here ](https://github.com/activerecord-hackery/ransack_demo )).
If you're looking for something that simplifies query generation at the model
or controller layer, you're probably not looking for Ransack (or MetaSearch,
for that matter). Try [Squeel ](https://github.com/activerecord-hackery/squeel )
instead.
2011-06-06 21:32:03 -04:00
## Getting started
2014-08-17 18:36:50 -04:00
Because ActiveRecord has been evolving quite a bit, your friendly Ransack is
available in several flavors! Take your pick:
2014-07-24 11:38:27 -04:00
2014-08-17 18:49:55 -04:00
In your Gemfile, for the last officially released gem for Rails 3.x, 4.0 and 4.1:
2014-07-24 11:38:27 -04:00
```ruby
gem 'ransack'
```
Or if you want to use the latest updates on the Ransack master branch:
2011-06-06 21:32:03 -04:00
2013-05-04 01:13:46 -04:00
```ruby
2014-07-25 05:50:47 -04:00
gem 'ransack', github: 'activerecord-hackery/ransack'
2013-05-04 01:13:46 -04:00
```
2012-04-11 14:20:46 -04:00
2014-08-17 18:36:50 -04:00
If you are using Rails 4.1, you may prefer the dedicated [Rails 4.1 branch ](https://github.com/activerecord-hackery/ransack/tree/rails-4.1 ) which
contains the latest updates, supports only 4.1, and is lighter and somewhat
faster:
2012-04-11 14:20:46 -04:00
2013-05-04 01:13:46 -04:00
```ruby
2014-07-24 11:38:27 -04:00
gem 'ransack', github: 'activerecord-hackery/ransack', branch: 'rails-4.1'
2013-12-06 18:02:40 -05:00
```
2014-08-17 18:36:50 -04:00
Similarly, if you are using Rails 4.0, you may prefer the dedicated [Rails 4 branch ](https://github.com/activerecord-hackery/ransack/tree/rails-4 ) for the
same reasons:
2013-12-06 18:02:40 -05:00
```ruby
2014-07-24 11:38:27 -04:00
gem 'ransack', github: 'activerecord-hackery/ransack', branch: 'rails-4'
2013-07-02 05:27:14 -04:00
```
2014-08-17 18:36:50 -04:00
Last but definitely not least, an experimental [Rails 4.2 branch ](https://github.com/activerecord-hackery/ransack/tree/rails-4.2 ) is
2014-08-17 18:49:55 -04:00
available for those on the edge (please see the note below in the I18n
section about an important change with Rails 4.2):
2013-12-30 18:36:37 -05:00
```ruby
2014-07-24 11:38:27 -04:00
gem 'ransack', github: 'activerecord-hackery/ransack', branch: 'rails-4.2'
2013-12-30 18:36:37 -05:00
```
2013-12-18 14:17:06 -05:00
2011-06-06 21:32:03 -04:00
## Usage
Ransack can be used in one of two modes, simple or advanced.
### Simple Mode
2014-05-11 11:10:08 -04:00
This mode works much like MetaSearch, for those of you who are familiar with
it, and requires very little setup effort.
2011-06-06 21:32:03 -04:00
If you're coming from MetaSearch, things to note:
2014-05-11 11:10:08 -04:00
1. The default param key for search params is now `:q` , instead of `:search` .
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]
(https://github.com/activerecord-hackery/ransack/wiki/Configuration).
2. `form_for` is now `search_form_for` , 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
`Search#result` . If passed `distinct: true` , `result` will generate a `SELECT
DISTINCT` to avoid returning duplicate rows, even if conditions on a join
would otherwise result in some.
Please note that for many databases, a sort on an associated table's columns
will result in invalid SQL with `distinct: true` -- in those cases, you're on
your own, and will need to modify the result as needed to allow these queries
to work. Thankfully, 9 times out of 10, sort against the search's base is
sufficient, though, as that's generally what's being displayed on your
results page.
2011-06-06 21:32:03 -04:00
2014-05-11 11:39:38 -04:00
####In your controller
2011-06-06 21:32:03 -04:00
2013-05-04 01:13:46 -04:00
```ruby
def index
@q = Person.search(params[:q])
2013-08-06 13:47:59 -04:00
@people = @q .result(distinct: true)
2013-05-04 01:13:46 -04:00
end
```
2014-05-11 11:39:38 -04:00
or without `distinct:true` , for sorting on an associated table's columns (in
this example, with preloading each Person's Articles and pagination):
2014-05-11 11:10:08 -04:00
```ruby
def index
@q = Person.search(params[:q])
@people = @q .result.includes(:articles).page(params[:page])
end
```
2011-06-06 21:32:03 -04:00
2014-05-11 11:39:38 -04:00
####In your view
2011-06-06 21:32:03 -04:00
2014-05-11 11:10:08 -04:00
The two primary Ransack view helpers are `search_form_for` and `sort_link` ,
2014-08-17 18:36:50 -04:00
which are defined in
[Ransack::Helpers::FormHelper ](lib/ransack/helpers/form_helper.rb ).
2014-05-11 11:10:08 -04:00
2014-08-17 18:49:55 -04:00
#####1. Ransack's `search_form_for` helper replaces `form_for` for creating the view search form:
2014-05-11 11:31:09 -04:00
2013-05-04 01:13:46 -04:00
```erb
< %= search_form_for @q do |f| %>
< %= f.label :name_cont %>
2014-05-11 11:10:08 -04:00
< %= f.search_field :name_cont %>
2013-05-04 01:13:46 -04:00
< %= f.label :articles_title_start %>
2014-05-11 11:10:08 -04:00
< %= f.search_field :articles_title_start %>
2013-05-04 01:13:46 -04:00
< %= f.submit %>
< % end %>
```
2011-06-06 21:32:03 -04:00
2014-05-11 11:10:08 -04:00
`cont` (contains) and `start` (starts with) are just two of the available
search predicates. See [Constants]
2014-08-17 18:36:50 -04:00
(https://github.com/activerecord-hackery/ransack/blob/master/lib/ransack/constants.rb)
for a full list and the [wiki]
(https://github.com/activerecord-hackery/ransack/wiki/Basic-Searching)
for more information.
2012-03-29 10:50:36 -04:00
2014-05-11 11:39:38 -04:00
The `search_form_for` answer format can be set like this:
2014-04-21 11:23:50 -04:00
```erb
< %= search_form_for(@q, format: :pdf) do |f| %>
< %= search_form_for(@q, format: :json) do |f| %>
```
2014-08-17 18:49:55 -04:00
#####2. Ransack's `sort_link` helper creates table headers that are sortable links:
2014-05-11 11:10:08 -04:00
```erb
< %= content_tag :th, sort_link(@q, :name) %>
2014-05-11 11:31:09 -04:00
```
Additional options can be passed after the column attribute, like a different
column title or a default sort order:
```erb
< %= content_tag :th, sort_link(@q, :name, 'Last Name', default_order: :desc) %>
2014-05-11 11:10:08 -04:00
```
2011-06-06 21:32:03 -04:00
### Advanced Mode
2014-05-11 11:10:08 -04:00
"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. :(
2011-06-06 21:32:03 -04:00
This means you'll need to tweak your routes...
2013-05-04 01:13:46 -04:00
```ruby
resources :people do
collection do
2013-08-06 13:47:59 -04:00
match 'search' => 'people#search', via: [:get, :post], as: :search
2013-05-04 01:13:46 -04:00
end
end
```
2011-06-06 21:32:03 -04:00
... and add another controller action ...
2013-05-04 01:13:46 -04:00
```ruby
def search
index
render :index
end
```
2012-03-29 10:50:36 -04:00
2011-06-06 21:32:03 -04:00
... and update your `search_form_for` line in the view ...
2013-05-04 01:13:46 -04:00
```erb
2013-08-06 13:47:59 -04:00
< %= search_form_for @q , url: search_people_path,
html: { method: :post } do |f| %>
2013-05-04 01:13:46 -04:00
```
2011-06-06 21:32:03 -04:00
2014-04-28 10:49:26 -04:00
Once you've done so, you can make use of the helpers in [Ransack::Helpers::FormBuilder ](lib/ransack/helpers/form_builder.rb ) to
2011-06-11 14:22:41 -04:00
construct much more complex search forms, such as the one on the
2013-12-18 14:45:49 -05:00
[demo page ](http://ransack-demo.heroku.com ) (source code [here ](https://github.com/activerecord-hackery/ransack_demo )).
2011-06-06 21:32:03 -04:00
2014-03-26 11:13:55 -04:00
### Ransack #search method
2014-05-11 11:10:08 -04:00
Ransack will try to to make `#search` available in your models, but in the case
that `#search` has already been defined, you can use `#ransack` instead. For
example the following would be equivalent:
2014-03-26 11:13:55 -04:00
2014-04-11 22:44:42 -04:00
```ruby
2014-03-26 11:13:55 -04:00
Article.search(params[:q])
Article.ransack(params[:q])
```
2012-10-06 17:14:47 -04:00
### has_many and belongs_to associations
You can easily use Ransack to search in associated objects.
Given you have these associations ...
2013-05-04 01:13:46 -04:00
```ruby
class Employee < ActiveRecord::Base
belongs_to :supervisor
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
# has attribute last_name:string
end
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
class Department < ActiveRecord::Base
has_many :supervisors
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
# has attribute title:string
end
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
class Supervisor < ActiveRecord::Base
belongs_to :department
has_many :employees
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
# has attribute last_name:string
end
```
2012-10-06 17:14:47 -04:00
... and a controller ...
2013-05-04 01:13:46 -04:00
```ruby
class SupervisorsController < ApplicationController
def index
@search = Supervisor.search(params[:q])
2014-05-11 11:39:38 -04:00
@supervisors = @search .result.includes(:department, :employees)
2013-05-04 01:13:46 -04:00
end
end
```
2012-10-06 17:14:47 -04:00
... you might set up your form like this ...
2013-05-04 01:13:46 -04:00
```erb
< %= search_form_for @search do |f| %>
< %= f.label :last_name_cont %>
2014-05-11 11:31:09 -04:00
< %= f.search_field :last_name_cont %>
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
< %= f.label :department_title_cont %>
2014-05-11 11:31:09 -04:00
< %= f.search_field :department_title_cont %>
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
< %= f.label :employees_last_name_cont %>
2014-05-11 11:31:09 -04:00
< %= f.search_field :employees_last_name_cont %>
2012-10-06 17:14:47 -04:00
2013-05-04 01:13:46 -04:00
< %= f.submit "search" %>
< % end %>
2014-05-11 11:31:09 -04:00
...
< %= content_tag :table %>
< %= content_tag :th, sort_link(@q, :last_name) %>
< %= content_tag :th, sort_link(@q, 'departments.title') %>
< %= content_tag :th, sort_link(@q, 'employees.last_name') %>
< % end %>
2013-05-04 01:13:46 -04:00
```
2012-10-06 17:14:47 -04:00
2014-05-09 17:28:43 -04:00
### Using Ransackers to add custom search functions via Arel
2014-05-07 18:03:04 -04:00
The main premise behind Ransack is to provide access to
2014-05-11 11:10:08 -04:00
**Arel predicate methods**. Ransack provides special methods, called
_ransackers_, for creating additional search functions via Arel. More
information about `ransacker` methods can be found [here in the wiki]
2014-05-07 18:03:04 -04:00
(https://github.com/activerecord-hackery/ransack/wiki/Using-Ransackers).
Feel free to contribute working `ransacker` code examples to the wiki!
2014-05-09 17:28:43 -04:00
### Using SimpleForm
2014-02-21 09:27:18 -05:00
2014-05-11 11:10:08 -04:00
If you want to combine form builders of ransack and SimpleForm, just set the
RANSACK_FORM_BUILDER environment variable before Rails started, e.g. in
``config/application.rb`` before ``require 'rails/all'`` and of course use
``gem 'simple_form'`` in your ``Gemfile``:
2014-02-21 09:27:18 -05:00
```ruby
require File.expand_path('../boot', __FILE__ )
ENV['RANSACK_FORM_BUILDER'] = '::SimpleForm::FormBuilder'
require 'rails/all'
```
2014-06-22 05:15:10 -04:00
### Authorization
2014-07-25 05:50:47 -04:00
By default, Ransack exposes search on any model column, so make sure you
2014-08-17 18:36:50 -04:00
sanitize your params and only pass the allowed keys. Alternately, you can
define these class methods on your models to apply selective authorization
2014-07-25 05:50:47 -04:00
based on a given auth object:
2014-06-22 05:15:10 -04:00
2014-08-01 00:47:12 -04:00
* `def self.ransackable_attributes(auth_object = nil)`
* `def self.ransackable_associations(auth_object = nil)`
* `def self.ransackable_scopes(auth_object = nil)`
* `def self.ransortable_attributes(auth_object = nil)` (for sorting)
2014-06-22 05:15:10 -04:00
Any values not included in the arrays returned from these methods will be
2014-07-25 05:50:47 -04:00
ignored. The auth object should be optional when building the search, and is
2014-06-22 05:15:10 -04:00
ignored by default:
```
2014-06-23 17:59:25 -04:00
Employee.search({ salary_gt: 100000 }, { auth_object: current_user })
2014-06-22 05:15:10 -04:00
```
### Scopes
Searching by scope requires defining a whitelist of `ransackable_scopes` on the
model class. By default all class methods (e.g. scopes) are ignored. Scopes
will be applied for matching `true` values, or for given values if the scope
accepts a value:
```
2014-06-23 17:59:25 -04:00
Employee.search({ active: true, hired_since: '2013-01-01' })
2014-06-22 05:15:10 -04:00
```
2014-05-09 17:28:43 -04:00
### I18n
2013-10-07 07:47:52 -04:00
2014-05-11 11:10:08 -04:00
Ransack translation files are available in
[Ransack::Locale ](lib/ransack/locale ). You may also be interested in one of the
many translations for Ransack available at
http://www.localeapp.com/projects/2999.
2012-10-06 17:14:47 -04:00
2014-08-17 18:36:50 -04:00
If you are using Ransack with Rails 4.2.0.alpha after August 14, 2014,
2014-08-17 18:49:55 -04:00
[Rails commit dfc3f88 ](https://github.com/rails/rails/commit/dfc3f88 ) changed
how `placeholder` options in `search_field` / `text_field` helpers in Ransack
2014-08-17 18:36:50 -04:00
search forms are handled by Rails. The following no longer works with Rails 4.2.0:
```erb
< %= search_form_for @q do |f| %>
< %= f.search_field :name_cont, placeholder: t(:name) %>
< %= f.search_field :articles_title_start, placeholder: t('.title') %>
< %= f.submit %>
< % end %>
```
Instead of the placeholders being displayed correctly, the supplied values are
ignored and a `humanized` version of the search method is displayed instead
(i.e. "Name cont" and "Articles title start").
The solution I've found so far is to pass `placeholder: true` instead and
update the I18n files with translations by search method, scoped by
`'helpers.placeholder.q'` , as shown:
```erb
< %= search_form_for @q do |f| %>
< %= f.search_field :name_cont, placeholder: true %>
< %= f.search_field :articles_title_start, placeholder: true %>
< %= f.submit %>
< % end %>
```
```
# en.yml
helpers:
placeholder:
q:
name_cont: "Name contains..."
articles_title_start: "Article title starts with..."
```
2011-06-06 21:32:03 -04:00
## Contributions
2012-03-29 10:50:36 -04:00
To support the project:
2011-06-06 21:32:03 -04:00
2014-05-11 11:10:08 -04:00
* Use Ransack in your apps, and let us know if you encounter anything that's
broken or missing. A failing spec is awesome. A pull request with tests that
pass is even better! Before filing an issue or pull request, be sure to read
the [Contributing Guide ](CONTRIBUTING.md ).
* 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!
2011-06-06 21:32:03 -04:00
## Copyright
2014-01-02 04:24:56 -05:00
Copyright © 2011-2014 [Ernie Miller ](http://twitter.com/erniemiller )