How do I write a UNION chain with ActiveRelation?

后端 未结 4 546
小蘑菇
小蘑菇 2021-02-05 13:23

I need to be able to chain an arbitrary number of sub-selects with UNION using ActiveRelation.

I\'m a little confused by the ARel implementation of this, si

4条回答
  •  终归单人心
    2021-02-05 13:42

    I like Squeel. But don't use it. So I came to this solution (Arel 4.0.2)

    def build_union(left, right)
      if right.length > 1
        Arel::Nodes::UnionAll.new(left, build_union(right[0], right[1..-1]))
      else
        Arel::Nodes::UnionAll.new(left, right[0])
      end
    end
    
    managers = [select_manager_1, select_manager_2, select_manager_3]
    build_union(managers[0], managers[1..-1]).to_sql
    # => ( (SELECT table1.* from table1)
    #    UNION ALL
    #    ( (SELECT table2.* from table2)
    #    UNION ALL
    #    (SELECT table3.* from table3) ) )
    

提交回复
热议问题