Rails Activerecord Relation: using subquery as a table for a SQL select statement

Use the from() method from the Active Record interface.

For example:

@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")

Then use it like this in the outer query:

@query = OtherModel.from("(#{@subquery.to_sql}) table_name, other_model_table, etc ...").where(:field => table_name.alias_a) ...etc.

This one is more elegant:

@subquery = Model.balalalala
@query = OtherModel.from(@subquery, :sub_query).where(sub_query: {column_b: balalala}).order('sub_query.column_a')