Rails - 构建条件语句

时间:2011-10-05 18:28:53

标签: ruby-on-rails

我正在努力建立我的条件:

conditions = {}
conditions[:doors] = 4
conditions[:type] = "sedan"

Cars.find(:all, :conditions=>conditions)

我如何为'LIKE'条件添加条件:

conditions[:color] NOT LIKE '%black%'

1 个答案:

答案 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注入的输入。