问题描述
我知道有3种主要的符号用于为 ActiveRecord方法:
I know there are 3 main notations for supplying arguments to the where
ActiveRecord method:
- 纯字符串
- Array
- 哈希
指定和
表示其中
方法很简单:
# 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})
为此指定
方法让我很讨厌哈希语法。 或
,其中
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- 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,您可以使用方法:
Person.where(name: 'Neil').or(Person.where(age: 27))
使用以及。 才能确保 default_scope
不包含在 where_values
中。否则来自 default_scope
和的谓词,其中
将与
或$ c $链接c>运算符:
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:
-
(Ruby on Rails 5的backport
.or
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
)
使用:
Person.where(
Person.arel_table[:name].eq('Neil').or(
Person.arel_table[:age].eq(27)
)
)
使用带名称par的准备好的语句ameters:
Use prepared statements with named parameters:
Person.where('name = :name or age = :age', name: 'Neil', age: 27)
这篇关于ActiveRecord或查询哈希符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!