【问题标题】:In Arel, how can I combine a bunch of conditions with OR?在 Arel 中,如何将一堆条件与 OR 结合起来?
【发布时间】:2012-02-11 02:32:13
【问题描述】:

我有一个类似这样的设置:

  table = self.arel_table
  nodes = [1,2,3].collect do |c|
    table[:foo].eq(c).and( table[:bar].eq(c) )
  end

然后,我希望将这些条件片段组合起来以生成类似于以下内容的 SQL:

WHERE (foo = 1 AND bar = 1) OR (foo = 2 AND bar = 2) OR (foo = 3 AND bar = 3)

到目前为止我最接近的是:

nodes.inject(nodes.shift) {|memo, node| memo.or( Arel::Nodes::Grouping.new(node) ) }

我以不同的方式尝试了Arel::Nodes::Grouping.new,但它从来没有按照我想要的方式分组。

【问题讨论】:

标签: ruby-on-rails ruby arel


【解决方案1】:

您可能想使用squeel,无需重新发明轮子。

有了它,您的案例将类似于:Model.where {foo.like_any nodes}

编辑:

如果你定义自己的 sifter 会容易得多,看起来像这样(如果你启用原生扩展):

nodes.each do |node|
  where{foo == node & bar == node}
end

【讨论】:

    【解决方案2】:
    table = self.arel_table
    Person.where([1,2,3].collect { |c| table[:foo].eq(c).and(table[:bar].eq(c)) }.map(&:to_sql).join(" OR "))
    

    【讨论】:

    猜你喜欢
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    相关资源
    最近更新 更多