Monthly Archives: May 2009

[Ruby on Rails] Custom search with act_as_seekable gem/plugin

http://github.com/innetra/acts_as_seekable
A common problem most of us have when creating an application is adding search methods. Some times we need to allow users to perform a search involving order paramaters, filter and a free text input for keywords or person name in case you are perfoming people search.
Rails it self provided us with some cool tools to do this, named scopes are very usefull since you can chain them to get better results, a good example would be Person.doctor.retired returning a collection of Retired Doctors (if we got those named_scopes defined).
So a few days ago I created a small plugin that adds a “seek” method to all the models you need. This seek method will recieve a hash as parameter, in this hash should look like this:
{:filter => ‘named_scope_name_for_filter’, :search => ‘Text to search’, :order => ‘column ORDER’ }

Here is a small example:
db/migrate/XXXXXXXX_create_people.rb

class CreatePeople < ActiveRecord::Migration
def self.up
create_table :people do |t|
t.string :name
t.integer :age
t.boolean :retired
t.string :profession
t.timestamps
end
end
def self.down
drop_table :people
end
end

app/models/person.rb
class Person < ActiveRecord::Base
acts_as_seekable :paginate => true
named_scope :doctor, :conditions => {:profession => 'Doctor'}
named_scope :retired, :conditions => {:retired => true}
named_scope :elder, :conditions => {:age => 70..200}
end

app/controllers/people_controller.rb
class PeopleController < ActionController::Base
def index
@people = Person.seek(params)
end
end

The plugin/gem can be found at http://github.com/innetra/acts_as_seekable.
A better example can be found at http://github.com/gusortiz/acts_as_seekable_example
clone it, test it, do whatever you want with it.

Enjoy
Leave comments please, that way I know I’m not talking to the wall. :O

Advertisements