我正在努力建立我的条件:
conditions = {}
conditions[:doors] = 4
conditions[:type] = "sedan"
Cars.find(:all, :conditions=>conditions)
我如何为'LIKE'条件添加条件:
conditions[:color] NOT LIKE '%black%'
答案 0 :(得分:2)
如果您有Rails 3+,请考虑使用新的AREL语法进行部分查询构建:
records = Car.where(:doors => 4, :type => "sedan")
records = records.where("color NOT LIKE ?", "%black%")
但如果您仍在使用Rails 2.3,则语法如下:
clauses = ["doors = ?", "type = ?"]
conditions = [4, 'sedan']
if some_reason
clauses << "color NOT LIKE ?"
conditions << "%robert%"
end
Cars.find(:all, :conditions => [clauses.join(" AND" ), *conditions])
肯定比AREL语法更烦人。
这种语法的另一个好处是,当ActiveRecord替换?
时,它将清理SQL注入的输入。