Skip to content
Advertisement

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

Can somebody help me figure out how to write the following SQL using Rails (I’m using Rails 4) Activerecord methods? I know you can do this with find_by_sql but I’d like to preserve the active record relation. Here’s the sql for a postGreSQL db that I’m trying to create:

For my subquery, I have the following (which generates the sql of the subquery above):

But, I can’t figure out how to write a select statement that uses @subquery as the table for the outer select statement.

Advertisement

Answer

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

For example:

Then use it like this in the outer query:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement