Use o
from()
método da interface do Active Record. Por exemplo:
@subquery = table_a.select("DISTINCT ON(table_a.id) table_a.name as alias_a, table_b.time")
@subquery = @subquery.joins("LEFT OUTER JOIN table_b ON table_a.id = table_b.id")
@subquery = @subquery.order("table_a.id, table_b.time asc")
Em seguida, use-o assim na consulta externa:
@query = OtherModel.from("(#{@subquery.to_sql}) table_name, other_model_table, etc ...").where(:field => table_name.alias_a) ...etc.