ActiveRecord或查询哈希符号 [英] ActiveRecord OR query Hash notation

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

问题描述

我知道有3种主要的符号用于为 哪里 ActiveRecord方法:

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


  1. 纯字符串

  2. Array

  3. 哈希

指定表示其中方法很简单:

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


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

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


  • 使用 where_values 以及 减少 未限制范围 仅适用于Rails 4.1+ 才能确保 default_scope 不包含在 where_values 中。否则来自 default_scope 的谓词,其中将与运算符:

  • 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

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


  • 使用带名称par的准备好的语句ameters:

  • Use prepared statements with named parameters:

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


  • 这篇关于ActiveRecord或查询哈希符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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