Nested queries in Arel

后端 未结 5 1293
时光取名叫无心
时光取名叫无心 2020-12-08 03:23

I am attempting to nest SELECT queries in Arel and/or Active Record in Rails 3 to generate the following SQL statement.

SELECT sorted.* FROM (SELECT * FROM p         


        
5条回答
  •  悲哀的现实
    2020-12-08 04:13

    Here's my approach to temporary tables and Arel. It uses Arel#from method passing in the inner query with Arel#to_sql.

    inner_query = YourModel.where(:stuff => "foo")
    outer_query = YourModel.scoped  # cheating, need an ActiveRelation
    outer_query = outer_query.from(Arel.sql("(#{inner_query.to_sql}) as results")).
                              select("*")
    

    Now you can do some nice things with the outer_query, paginate, select, group, etc...

    inner_query ->

    select * from your_models where stuff='foo'
    

    outer_query ->

    select * from (select * from your_models where stuff='foo') as results;
    

提交回复
热议问题