Easily Search on ActiveRecord Attributes

Rails’s named_scopes are great, and the ability to chain named_scopes together are even better. I am sure many of us have done something like this before:

   User.active.live_in('Virginia') 

That would give you the active users who live in the state of Virginia. You would define something like these in your User model:

   named_scope :active, lambda { |status| { :conditions => { :status => status } } }   named_scope :live_in lambda { |state| { :conditions => { :state => state } } } 

One recent client project has a model where the database table has 30-something columns. Doing these named_scopes became tedious and repetitive. That makes it not fun anymore.

So Dave Pranata and I wrote the searchable_attributes Rails plugin so we could stop worrying about explicitly defining these named_scopes once and for all.

To use it, you just install it like any other Rails plugin:

 script/plugin install git://github.com/rayvinly/searchable_attributes.git 

The plugin will automatically define a bunch of named_scopes for you if you include this in your model:

 class User < ActiveRecord::Base   searchable_attributes end 

You can then search on your models with something like this:

   def index     @users = User.with_first_name_equal('Gilbert').with_last_name_equal_if_not_null('Arenas').with_address_like('Main Street').with_age_greater_than(25).with_state_equal(['VA', 'MD', 'DC']).with_position_end_with('Guard').with_salary_within_inclusive((100..10000)).with_injured_equal(true).with_join_date_greater_than_or_equal_to(5.years.ago)   end 

Take a look in the plugin’s lib/searchable_attributes.rb for a list of automatically defined named_scopes.