Adding LIKE Criteria to the Rails Conditions Block

Consider the following code to throw when searching for AR:

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 the LIKE criterion for the attribute 'profile'. How can I do this, since it is obvious that LIKE is usually executed through an array and not a hash key.

+5
source share
3 answers

You can combine your model with hash conditions, and then execute findover an area with array conditions:

YourModel.scoped(:conditions => conditions).all(:conditions => ["profile like ?", profile])
+5
source

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]
+1
source

, , , :

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

, :)

0

All Articles