在activerecord哈希条件中添加高级语句

时间:2014-11-05 16:24:13

标签: ruby activerecord

我有一个哈希女巫包含许多条件,我想添加到它另一个条件,使用优越的声明我怎么能这样做 例如

    // conditions is a hash of conditions
conditions[:id]="> 100"
personels=Personel.find(:all, :conditions=>conditions)

1 个答案:

答案 0 :(得分:0)

通常(不确定我是否完全理解您的目标)您在Array中存储了多个条件,然后您只需使用数组<<附加运算符添加更多条件,类似于:

条件是数组:

conditions = []
conditions << "id > '100'"
conditions << "NAME LIKE '%#{params[:name]}%'"
#
# ... more conditions here
#
conditions = conditions.join(' AND ')
Personel.where(conditions)

条件是哈希:

conditions = {}
conditions[:id] = "> '100'"
conditions[:NAME] = "LIKE '%#{params[:name]}%'"
#
# ... more conditions here
#
conditions = conditions.map{|k,v| "#{k} #{v}"}.join(' AND ')
Personel.where(conditions)