我知道为where ActiveRecord方法提供参数有三种主要符号:

  1. 纯弦
  2. 大堆
  3. 搞砸

where方法指定and是直截了当的:

# 纯弦 notation
Person.where("name = 'Neil' AND age = 27")

# 大堆 notation
Person.where(["name = ? AND age = ?", 'Neil', 27])

# 搞砸 notation
Person.where({name: "Neil", age: 27})

为这个where方法指定or让我很难理解散列语法.可能吗?

# 纯弦 notation
Person.where("name = 'Neil' OR age = 27")

# 大堆 notation
Person.where(["name = ? OR age = ?", 'Neil', 27])

# 搞砸 notation DOESN'T WORK
Person.where({name: "Neil" OR age: 27})

推荐答案

有5个选项可以被视为«哈希符号»的实现(最后两个有点像哈希-ish):

  1. 使用Ruby on Rails 5,您可以使用ActiveRecord::Relation#or方法进行以下链接:

    Person.where(name: 'Neil').or(Person.where(age: 27))
    
  2. where_valuesreduce一起使用.unscoped方法是确保where_values中不包括default_scope所必需的only for Rails 4.1+.否则,来自default_scopewhere的谓词将与or运算符链接:

    Person.where( 
      Person.unscoped.where(name: ['Neil'], age: [27]).where_values.reduce(:or) 
    )
    
  3. 安装实现这些或类似功能的第三方插件,例如:

    • Where Or (backport of the Ruby on Rails 5 101 feature mentioned above)

    • 一百

    • 一百

    • 一百

    • 一百

  4. 使用Arel:

    Person.where( 
      Person.arel_table[:name].eq('Neil').or(
        Person.arel_table[:age].eq(27)
      ) 
    )
    
  5. 将准备好的语句与命名参数一起使用:

    Person.where('name = :name or age = :age', name: 'Neil', age: 27)
    

Ruby-on-rails相关问答推荐

错误原始错误:未安装 ImageMagick/GraphicsMagick

File.open,写入和保存?

Rails 模型方法 self.与普通

从 Rails 生成 PDF

使用 Devise 令牌登录,这是内置的吗?

在 ID 存在时获取表的未知主键

Rails 文章助手 - a 或 an

通过字符串获取 ActiveRecord 对象的属性

我如何找出为什么我不能#destroy() 记录?

Rails - 具有空数组的强参数

Ruby中的参数化获取请求?

我怎样才能看到水豚在失败的黄瓜步骤中发现了什么?

Mongoid OR 查询语法

从 Rails 中的 ActiveRecord::RecordNotFound 救援

Rails:每个环境的初始化程序?

在任何来源中都找不到 thread_safe-0.3.0

扩展 Devise SessionsController 以使用 JSON 进行身份验证

如何在 Rails 表单中将复选框和标签保持在同一行?

ruby on rails 如何处理 NaN

如何创建一个 ruby​​ Hello 世界?