Simple Search Rails plugin

SimpleSearch brings simple search to ActiveRecord. It ads simple_search named scope that accepts query as parameter.

The idea is that you provide the query and plugin does the rest (splits query to keywords and compose where statement).

This can be very useful in case you just want to filter list of records by some query, you have autocomplete field, … or something similar.



  <% form_tag request.path, :method => 'get' do %>
    <%= text_field_tag :query, params[:query] %>
  <% end %>


  class User < ActiveRecord::Base
  # Columns: id, login, email, crypted_password, salt


  class UsersController < ApplicationController
    def index
      @users = User.simple_search(params[:query]).all

Query examples

Simple query

  # => SELECT * FROM "users" WHERE ( LIKE '%vlado%' OR users.login LIKE '%vlado%' OR LIKE '%vlado%' OR users.crypted_password LIKE '%vlado%' OR users.salt LIKE '%vlado%')

You can also provide :columns => :column1, :column2, … option to limit search only to those columns

  class User  :login, :email

  # => SELECT * FROM "users" WHERE (users.login LIKE '%vlado%' OR LIKE '%vlado%')

More complex query

  User.simple_search("vlado, cingel")
  # will search for users matching 'vlado' and 'cingel' keywords
  # => SELECT * FROM "users" WHERE ((users.login LIKE '%vlado%' OR LIKE '%vlado%') AND (users.login LIKE '%cingel%' OR LIKE '%cingel%'))

NOTE: With proper use of indexes this plugin can work quite well in most cases, but in case you have a large and complex database it is usually much better idea to use some search daemon like Thinking Sphinx.

More info

2 thoughts on “Simple Search Rails plugin

  1. Hi
    I have tried your plug-in, a first I wouldn’t work. But then I added the hooks in init.rb and it started working. So you might need to included that in your code

    #in init.rb
    require ‘active_record’
    require ‘simple_search’
    ActiveRecord::Base.send(:extend, SimpleSearch::ClassMethods)



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s