【问题标题】:Cannot programmatically combine AND and OR conditions using Arel无法使用 Arel 以编程方式组合 AND 和 OR 条件
【发布时间】:2013-05-14 10:47:46
【问题描述】:

鉴于使用 Arel 运算符(例如 .eq)生成的 SQL 条件 cond1、cond2 和 cond3,我似乎无法使用 Arel 来生成 SQL:

SELECT * FROM <table> WHERE (cond1 AND cond2) OR cond3

这是因为与条件一起使用.where(),但你不能然后.or() .where() 的结果。您只能在 .where() 中同时使用 .or() 条件。 IE。 .where 和 .or 不在同一个“级别”上,我猜想需要一个与 .or() 级别相同的专用 .and() 方法。

请注意,(cond1 AND cond2) 周围的括号表示这些条件同时被 AND 在一起,其中 OR cond3 是在循环的另一个迭代中添加的。它们对查询结果没有影响。

我已经阅读了 Arel README,但没有针对这种情况的示例,我无法弄清楚如何使用具有 OR 运算符 | 的 Squeel 动态构建此查询(在循环中)。

【问题讨论】:

    标签: ruby-on-rails-3.2 rails-activerecord arel


    【解决方案1】:

    Arel::Nodes::Grouping 将节点包裹在括号中。

    Arel::Nodes::Grouping.new(Arel::Nodes::And.new("blah", "there")).to_sql
    # => ('blah' AND 'there')
    

    【讨论】:

    • 谢谢,这似乎是唯一的方法。
    【解决方案2】:

    使用 Rails 5.2(应该使用 Rails 5+ 甚至更早版本)

    and_conds = Table.arel_table.grouping(
      Table.where(a: 'test', b: 2).arel.constraints.reduce(:and)
    )
    Table.where(and_conds).or(Table.where(a: 'blah'))
    

    结果类似于...

    select * from table where ((a = 'test' and b = 2) or a = 'blah')

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多