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.

Example

View

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

Model

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

Controller

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

Query examples

Simple query

  User.simple_search("vlado")
  # => SELECT * FROM "users" WHERE (users.id LIKE '%vlado%' OR users.login LIKE '%vlado%' OR users.email 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
  end

  
  User.simple_search("vlado")
  # => SELECT * FROM "users" WHERE (users.login LIKE '%vlado%' OR users.email 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 users.email LIKE '%vlado%') AND (users.login LIKE '%cingel%' OR users.email 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

http://github.com/cingel/simple_search

Advertisements

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)

    Sebastian

    Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s