【问题标题】:Creating a Rails query from a hash of user input从用户输入的哈希创建 Rails 查询
【发布时间】:2023-03-07 01:48:01
【问题描述】:

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

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

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

【问题讨论】:

  • 这看起来很危险。
  • 这就是你目前的全部吗?
  • 好的,你能发布你的代码吗?你尝试了什么?
  • 为什么问题被搁置?对我来说似乎很清楚,如果标准在给定答案中被明确列入白名单,这并不危险。
  • 我不知道如何才能更清楚地说明这个问题。也许如果有人告诉我他们需要知道什么,而不是投反对票并搁置我的问题,我可以解释一下。

标签: sql ruby-on-rails ruby activerecord


【解决方案1】:

如果我理解正确,这应该可以:

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

【讨论】:

  • 我不得不为我的确切代码稍微调整一下,但这或多或少正是我想要的。谢谢!
猜你喜欢
  • 2014-06-17
  • 2022-11-12
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 2015-06-03
  • 1970-01-01
相关资源
最近更新 更多