views:

111

answers:

3

Consider the following code which is to be thrown at an AR find:

conditions = []
conditions[:age] = params[:age] if params[:age].present?
conditions[:gender] = params[:gender] if params[:gender].present?

I need to add another condition which is a LIKE criteria on a 'profile' attribute. How can I do this, as obviously a LIKE is usually done via an array, not a hash key.

A: 

When you call your active record find, you send your conditions string first, then the hash with the values like :

:conditions => [ "age = :age AND gender = :gender AND profile LIKE :profile", conditions ]

that way you can keep doing what you are doing :)

Francisco Soto
what happened if params[:age] is not present?
Salil
Well I simplified, he can build the string just as he checks the params to fill his conditions hash.
Francisco Soto
+3  A: 

You can scope your model with hash conditions, and then perform find on scope with array conditions:

YourModel.scoped(:conditions => conditions).all(:conditions => ["profile like ?", profile])
Voyta
A: 

Follwing is ugly but it works

conditions = {} #This should be Hash
conditions[:age] = params[:age] if params[:age].present?
conditions[:gender] = params[:gender] if params[:gender].present?
conditions[:profile] = '%params[:profile]%' if params[:profile].present?

col_str =""  #this is our column names string for conditions array

col_str = "age=:age" if params[:age].present?
col_str+= (col_str.blank?)? "gender=:gender"  :" AND gender=:gender" if params[:gender].present?
col_str +=  (col_str.blank?) 'profile like :profile' : ' AND profile like :profile' if params[:profile].present?

:conditions=>[col_str , conditions]
Salil