将LIKE条件添加到Rails条件块

时间:2010-04-28 09:49:58

标签: ruby-on-rails ruby activerecord

考虑以下代码将在AR查找中抛出:

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

我需要在'profile'属性上添加另一个条件,即LIKE条件。我怎么能这样做,因为LIKE通常是通过数组完成的,而不是散列键。

3 个答案:

答案 0 :(得分:5)

您可以使用哈希条件对模型进行范围调整,然后对具有数组条件的范围执行find

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

答案 1 :(得分:1)

以下是丑陋但它有效

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]

答案 2 :(得分:0)

当您调用活动记录查找时,首先发送条件字符串,然后发送带有以下值的哈希:

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

这样你可以继续做你正在做的事情:)