代码之家  ›  专栏  ›  技术社区  ›  Neil Middleton

向rails条件块添加相似条件

  •  5
  • Neil Middleton  · 技术社区  · 15 年前

    考虑以下代码,这些代码将被抛出ar find:

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

    我需要在“profile”属性上添加另一个类似条件。很明显,like通常是通过数组而不是散列键来实现的。

    3 回复  |  直到 15 年前
        1
  •  5
  •   Tatjana N.    15 年前

    您可以使用哈希条件确定模型的范围,然后执行 find 在具有数组条件的作用域上:

    YourModel.scoped(:conditions => conditions).all(:conditions => ["profile like ?", profile])
    
        2
  •  1
  •   Salil    15 年前

    跟踪是丑陋的,但它是有效的

    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]
    
        3
  •  0
  •   Francisco Soto    15 年前

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

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

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