wvanbergen / scoped_search

Easily search you ActiveRecord models with a simple query language using a named scope.

Home | Edit | New

Search definition

Scoped search requires you to define the fields you want to search in:


class User < ActiveRecord::Base
  scoped_search :on => :first_name
  scoped_search :on => :last_name
end

Setting a field alias

It is possible to set a field alias, so that the alias can used in queries as well besides the actual field name:


class User < ActiveRecord::Base
  scoped_search :on => :username, :alias => :login
  scoped_search :on => :last_name, :aliases => [:surname, :name]
end

Setting the default operator

By default, scoped search uses the LIKE operator for textual fields, and the equals operator for other fields types. You can ovverride this behavior as follows:


class User < ActiveRecord::Base
  scoped_search :on => :username, :default_operator => :eq
end

Only search a field if it is explicitly mentioned

By default, scoped search will search in every specified field if no explicit field is given in the query. You can specify that scoped search should only look in a field if it is explicitly mentioned in a query (e.g. username = root instead of root).


class User < ActiveRecord::Base
  scoped_search :on => :username, :only_explicit => true
end

Searching in relations

It is possible to search in fields of related tables as well. Every Rails relationship type is supported: i.e. has_many, belongs_to, has_one, has_and_belongs_to_many, has_many => :through.


class User < ActiveRecord::Base
  belongs_to :account_type
  has_and_belongs_to_many :groups

  scoped_search :in => :groups, :on => :description
  scoped_search :in => :account_type, :on => :name
end

Shorthand notation

As shorthand, you can use an array to specify multiple fields in one line using an array:


class User < ActiveRecord::Base
  scoped_search :on => [:first_name, :last_name]
  scoped_search :in => :groups, :on => [:name, :description]
end

Backwards compatibility

For backwards compatibility, the following syntax to define fields is supported as well. If you are still using this syntax, please migrate to the new version described above.


class User < ActiveRecord::Base
  has_many :groups
  searchable_on :first_name, :last_name, :groups_name, :groups_description
end
Last edited by wvanbergen, Sun Aug 30 22:27:43 -0700 2009
Home | Edit | New
Versions: