f l a m e . o r g

organized flames

Find conditions from params[]

Posted on February 28, 2009

I have often wished to add a trivial search capability to my controllers which would allow searching on different fields. Without getting into a mess of many different if statements each of which has a different set of conditions, I use something much like the following:

 1 def index
 2   cond_hash = {}
 3   cond_strings = []
 4 
 5   if params[:search]
 6     cond_hash[:login] = "%#{params[:search]}%"
 7     cond_hash[:email] = "%#{params[:search]}%"
 8     cond_strings << "(login ILIKE :login OR email ILIKE :email)"
 9   end
10   if params[:search_address]
11     cond_hash[:address] = params[:search_address]
12     cond_strings << "(address == :address)"
13   end
14 
15   conditions = cond_strings.join(" AND ")
16   @users = User.all :conditions => [ conditions, cond_hash ]
17 end

It may be safer to use users.login, users.email, and users.address in the SQL-like strings above.