In Arel, how can I combine a bunch of conditions with OR?

家住魔仙堡 提交于 2020-01-04 13:34:13

问题


I have a setup similar to this:

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

I then want those condition fragments combined to end up with SQL similar to:

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

The closest I have so far is:

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

I've tried Arel::Nodes::Grouping.new in different ways but it never groups how I want.


回答1:


You might want to use squeel, no need to reinvent the wheel.

With it, your case would look something like: Model.where {foo.like_any nodes}

Edit:

It will be much easier if you define own sifter, which will look like this (if you enable native extensions):

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


来源:https://stackoverflow.com/questions/9237327/in-arel-how-can-i-combine-a-bunch-of-conditions-with-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!