从用户输入的哈希创建Rails查询

时间:2014-06-10 09:26:36

标签: sql ruby-on-rails ruby activerecord

我尝试使用可变数量的搜索条件为项目创建相当复杂的搜索引擎。用户输入被分类为散列数组。哈希包含以下信息:

{
    :column => "",
    :value => "",
    :operator => "", # Such as: =, !=, <, >, etc.
    :and_or => "", # Two possible values: "and" and "or"
}

如何遍历此数组并使用这些哈希中的信息进行ActiveRecord WHERE查询?

1 个答案:

答案 0 :(得分:4)

如果我理解正确,这应该有效:

query = criteria.map do |h| 
  "#{h[:column]} #{h[:operator]} ? #{h[:and_or]||''}" 
end.join(' ')

MyModel.where(query, *criteria.map { |h| h[:value] })

示例:

criteria = [{column: 'name', value: 'Jamie', operator: '=', and_or: 'and'}, 
            {column: 'age', value: 20, operator: '>' }]

将导致:

MyModel.where("name = ? and age > ? ", "Jamie", 20)

我会进一步建议验证columnoperatorand_or的值:

unless criteria.all? { |h| MyModel.column_names.include? h[:column]} &&
       criteria.all? { |h| %w(= != < >).include? h[:operator] } &&
       criteria.all? { |h| ['and', 'or', nil].include? h[:and_or] }
  raise InvalidQueryError
end