public
Description: Easily search you ActiveRecord models with a simple query language using a named scope.
Home | Edit | New

Usage

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


class User < ActiveRecord::Base
  searchable_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| ... }

If you want to load a lot or most of the columns in a table you can specify the except option:


class User < ActiveRecord::Base
  searchable_on :except => [:id, :created_at, :updated_at]  
end

Note: There is also an only option but it is the default and it is not required.

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
  searchable_on :first_name, :last_name, :notes_title, :notes_content
end

Leveraging named_scope

This functionality is build on named_scope. The searchable_on 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
  searchable_on :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)
Last edited by wvanbergen, Thu Jan 29 23:44:46 -0800 2009
Home | Edit | New
Versions: