问题
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