简体   繁体   English

Arel语法(此AND此)OR(此AND此)

[英]Arel syntax for ( this AND this) OR ( this AND this)

how would I do this in Arel ( this AND this) OR ( this AND this) 我将如何在Arel中执行此操作(此AND此)或(此AND此)

Context is rails 3.0.7 上下文是rails 3.0.7

Mike's answer was basically what you're looking for 迈克的回答基本上就是你要找的

class Model < ActiveRecord::Base
  def self.this_or_that(a1, a2, a3, a4)
    t = Model.arel_table
    q1 = t[:a].eq(a1).and(t[:b].eq(a2))
    q2 = t[:c].eq(a3).and(t[:d].eq(a4))
    where(q1.or(q2))
  end
end

some slides I put together on Arel 我在Arel上放了一些幻灯片

I'd put this all in a single where block. 我把这一切都放在一个块里面。 For example, here's a 'scope' based on a similar complex 'where' clause: 例如,这是一个基于类似复杂'where'子句的'范围':

class Foo < ActiveRecord::Base
  def self.my_complex_where(args)
    where("(col1 = ? AND col2 = ?) OR (col3 = ? AND col4 = ?)", 
          args[:val1], args[:val2], args[:val3], args[:val4])
  end
end

Alternatively, you could do it using this notation: 或者,您可以使用此表示法执行此操作:

class Foo < ActiveRecord::Base
  def self.my_complex_where(args)
    where("(col1 = :val1 AND col2 = :val2) OR (col3 = :val3 AND col4 = :val4)", 
          :val1 => args[:val1], 
          :val2 => args[:val2], 
          :val3 => args[:val3],
          :val4 => args[:val4])
  end
end

You need to drop down to more raw AREL 你需要下降到更原始的AREL

t = Model.arel_table
a = (t[:a].eq(nil).and(t[:b].eq(nil)))
b = (t[:a].not_eq(nil).and(t[:b].not_eq(nil)))
Model.where(a.and(b))

Besides the answers already given, you might also want to take a look at the gem ' squeel ' 除了已经给出的答案,你可能还想看看宝石' 吱吱 '

Example: 例:

Person.where{(name =~ 'Ernie%') & (salary < 50000) | (name =~ 'Joe%') & (salary > 100000)}

我不知道帮助方法,但你总是可以下载到(几乎)纯SQL

Client.where("orders_count = ? AND locked = ?", params[:orders], false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM