我的问题类似于this one ,但那里的答案都没有解决我的具体问题。
我想找到类似这样的对象:
conditions = {first_name: @search OR last_name: @search}
Stuff.where( conditions )
显然,这种语法是无效的,但这是我能想到的展示我想做的事情的最简单的方法。我想在复杂/复合条件下使用更简洁的哈希语法。
我知道你可以用像这样的“纯字符串条件”手写出来 Stuff.where("first_name=#{@search} OR last_name=#{@search}")
...但这不是我想知道的。
更新 看起来您可以对这样的数组执行 OR:Stuff.where( some_column: ["option1", "option2"])
。这是非常有用的知识,但它并不能解决我的问题,因为我需要将 OR 应用于不同的键=值对... key=value OR key=value
而不是 key =值或值
。
Update2 我不想使用 SQL 字符串的原因是因为我需要分几部分构建查询,而我不知道如何在转义插入的字符串的同时做到这一点变量。我还没有测试过,但我假设这行不通:
conditions = ["(project_id=? AND sent_to_api=1)", @project_id]
conditions = conditions + ["first_name=? OR last_name=?", @search, @search]
Stuff.where( conditions )
希望这是有道理的。有没有办法在保留 Rails 的内置 SQL 转义的同时使用 SQL 字符串语法完成我需要的操作?
最佳答案
一个可重用的方法如何为您安全地生成可怕的 SQL 字符串:
class ActiveRecord::Base
def self.in_any(value, *column_names)
raise 'At least one column must be supplied' unless column_names.present?
sql_fragment = column_names.map{|f| "#{quote_column_name(f)} = :search"}.join(" OR ")
where(sql_fragment, search: value)
end
end
Stuff.in_any(@search, :first_name, :last_name)
更新
如果您出于某种原因不想添加方法,您可以非常安全地即时执行此操作,而不必担心注入(inject)。在这种情况下(恕我直言)最优雅的方法是将过滤器链接在一起:
Stuff.where('project_id = ? AND sent_to_api = 1', @project_id).
where('first_name = :search OR last_name = :search', search: @search)
关于ruby-on-rails - rails 4 : how to use OR between conditions on find methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18722978/