ActiveRecord 或查询哈希符号

我知道为 where ActiveRecord 方法提供参数有3种主要的表示法:

  1. 纯弦
  2. 数组
  3. 大麻

where方法指定 and很简单:

# 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方法指定 or就是为散列语法做难题。这可能吗?

# 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})
22263 次浏览

有5个选项可以被认为是“散列表示法”的实现(最后两个是有点散列 -差不多吧) :

  1. 使用 RubyonRails 5,您可以使用 ActiveRecord::Relation#or方法执行以下链接:

    Person.where(name: 'Neil').or(Person.where(age: 27))
    
  2. 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)
    )
    
  3. Install third-party plugins that implement these or similar features, for example:

    • 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
      )
      
  4. Use Arel:

    Person.where(
    Person.arel_table[:name].eq('Neil').or(
    Person.arel_table[:age].eq(27)
    )
    )
    
  5. Use prepared statements with named parameters:

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

正如 potashin 所说,您可以使用另一个实现此功能的第三方插件。我已经使用 吱吱很长时间了,并且在这方面做得很好,还有更多的特性,比如复杂的子查询或连接。

这个问题使用了 Squeel:

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