I am performing a union over two subsets of my domain table with cnt
being a local variable, using arel 2.0.9 and squeel 0.8.5 as query interface.
def bla cnt
Domain.group { some_id }.select { `*` }.select { count(`*`).as(`cnt`) }.having { `cnt` >= cnt }
end
Now when building the union of two calls say cnt(1).union(cnt(1))
I get a Arel::Nodes::Union
instance.
How do I use this relation to actually get my results? Calling #each
yields the very same Arel::Nodes::Union
reference and #to_sql
results in an TypeError: Cannot visit Arel::Nodes::Union
.
Any ideas? I could write the query differently, e.g. by using conditio开发者_开发技巧nal logic (doable in arel?) ...
Not sure if I am understanding you right, but to get a union of two or more separate queries, you can use the followng approach:
scope :union, lambda { |a, b| where{id.in(Model.where{attr1.eq a}) | id.in(Model.where{attr2.eq b}) } }
It's a little ugly, but I am not aware of any other approach...
You need to convert the ActiveRecord::Relation
object into a Arel::Nodes::SelectStatement
, you can easily do this by way of Relation#ast
:
union = Arel::Nodes::Union.new( cnt(1).ast, cnt(1).ast )
Domain.find_by_sql( union.to_sql )
精彩评论