ActiveRecord OR 查询哈希表示法 [英] ActiveRecord OR query Hash notation
问题描述
我知道为 where<提供参数有 3 个主要符号/code>
ActiveRecord 方法:
I know there are 3 main notations for supplying arguments to the where
ActiveRecord method:
- 纯字符串
- 数组
- 哈希
为 where
方法指定 和
很简单:
Specifying and
for the where
method is straight forward:
# Pure String notation
Person.where("name = 'Neil' AND age = 27")
# Array notation
Person.where(["name = ? AND age = ?", 'Neil', 27])
# Hash notation
Person.where({name: "Neil", age: 27})
为相同的 where
方法指定 或
使我难以理解哈希语法.可能吗?
Specifying or
for this same where
method is stumping me for the hash syntax. Is it possible?
# Pure String notation
Person.where("name = 'Neil' OR age = 27")
# Array notation
Person.where(["name = ? OR age = ?", 'Neil', 27])
# Hash notation DOESN'T WORK
Person.where({name: "Neil" OR age: 27})
推荐答案
有 5 个选项可以被视为 «Hash notation» 的实现(最后两个有点像 hash-ish):
There are 5 options that could be considered as implementations of «Hash notation» (the last two are kinda hash-ish):
使用 Ruby on Rails 5,您可以使用
ActiveRecord::Relation#or
方法:
Person.where(name: 'Neil').or(Person.where(age: 27))
使用where_values
与 reduce
.unscoped
方法是必要的仅适用于 Rails 4.1+ 以确保 default_scope
未包含在 where_values
中.否则来自 default_scope
和 where
的谓词将与 or
运算符链接:
Use where_values
together with reduce
. The unscoped
method is necessary only for Rails 4.1+ to ensure default_scope
is not included in the where_values
. Otherwise predicates from both default_scope
and where
would be chained with the or
operator:
Person.where(
Person.unscoped.where(name: ['Neil'], age: [27]).where_values.reduce(:or)
)
安装实现这些或类似功能的第三方插件,例如:
Install third-party plugins that implement these or similar features, for example:
Where Or (向后移植 Ruby on Rails 5
.or
上面提到的特性)
Where Or (backport of the Ruby on Rails 5
.or
feature mentioned above)
Person.where{(name == 'Neil') | (age == 27)}
Person.where(name: 'Neil').or(age: 27)
Person.where.anyof(name: 'Neil', age: 27)
Person.where(
(SmartTuple.new(' or ') << {name: 'Neil', age: 27}).compile
)
使用Arel:
Person.where(
Person.arel_table[:name].eq('Neil').or(
Person.arel_table[:age].eq(27)
)
)
使用带有命名参数的准备好的语句:
Use prepared statements with named parameters:
Person.where('name = :name or age = :age', name: 'Neil', age: 27)
这篇关于ActiveRecord OR 查询哈希表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!