ActiveRecord OR 查询哈希表示法 [英] ActiveRecord OR query Hash notation

查看:25
本文介绍了ActiveRecord OR 查询哈希表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道为 where<提供参数有 3 个主要符号/code> ActiveRecord 方法:

I know there are 3 main notations for supplying arguments to the where ActiveRecord method:

  1. 纯字符串
  2. 数组
  3. 哈希

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):

  1. 使用 Ruby on Rails 5,您可以使用 ActiveRecord::Relation#or 方法:

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

  • 使用where_valuesreduce.unscoped 方法是必要的仅适用于 Rails 4.1+ 以确保 default_scope未包含在 where_values 中.否则来自 default_scopewhere 的谓词将与 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)

    Squeel

    Person.where{(name == 'Neil') | (age == 27)} 
    

  • RailsOr

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

  • ActiverecordAnyOf

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

  • SmartTuple

    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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆