Photo_12_small Alexander Jo... 2 posts

Hi Ryan:

How do you embed SELECT statements in a find method? In an SQL statement you will do it in the FROM clause, but I don’t know if Rails supports embedded SELECT statements.

Thanks,
Alex

 
Ryan_bates_cropped_small Ryan Bates 29 posts

Hi Alex,

Rails doesn’t provide a pretty way to do subqueries, but it’s just plain SQL so you can embed it directly. This is untested, but I believe you can use the :from option to do this.


Person.find(:all, :from => 'people, (SELECT ...)')

You can also put a subquery in :joins or :conditions depending on your needs. If all else fails, you can fall back to find_by_sql where you just pass a plain query.

 
Photo_12_small Alexander Jo... 2 posts

Ryan;

I appreciate your prompt reply and a thorough one too. I shall give it a try to your suggestions and see what fits the best in my app.

Thank you.

-Alex

3 posts, 2 voices