Skip to content
Dominic Cleal edited this page Jan 19, 2017 · 12 revisions

First, you have to specify in what columns should be searched:

class User < ActiveRecord::Base
  scoped_search on: [:first_name, :last_name]
end

Now, the search_for scope is available for queries. You should pass a query string to the scope.
This can be empty or nil, in which case all no search conditions are set (and all records will be returned).

User.search_for(params[:q]).each { |project| ... }

Search associated records

You can also search on associate models. This works with belongs_to, has_one, has_many,
has_many :through, and HABTM. For example if a User has_many Notes (title, content, created_at, updated_at)

class User < ActiveRecord::Base
  has_many: notes
  scoped_search on: [:first_name, :last_name]
  scoped_search relation: :notes, on: :title
  scoped_search relation: :notes, on: :content
end

For scoped_search 3.x and older, change `:relation` to `:in`.

Leveraging named_scope

This functionality is build on named_scope. The scoped_search statement creates
a named_scope search_for. Because of this, you can actually chain the call with
other scopes. For example, this can be very useful if you only want to search in
projects that are accessible by a given user.

class Project < ActiveRecord::Base
  scoped_search [:name, :description]
  named_scope :accessible_by, lambda { |user| ... }
end

# using chained named_scopes and will_paginate
Project.accessible_by(current_user).search_for(params[:q]).paginate(page: params[:page], include: :tasks)

Using order by and group

Optionally you can add a order and group directives to the search_for. Use the order to sort the
search result. Use group to get distinct results.

User.search_for(params[:q], order: 'first_name asc', group: 'user_id').each { |project| ... }

Autocompletion

Partial search queries can be autocompleted by scoped_search, giving the user a list of possible fields, operators and values.

> User.complete_for('first_name =')
=> ["first_name = John", "first_name = Jane"]

More information on Autocompletion, including how to integrate it into your UI with jQuery.

Advanced usage

The search definition (scoped_search) call accepts many options to change its behaviour, supporting a variety of features:

  • aliases or renamed search fields
  • default sorting options
  • external method implementations

Documentation for these features is available on the Search definition wiki page.