Possible Duplicate:
Ruby on Rails: How can i join with a derived table?
posts table
Table "public.posts"
Column | Type | Modifiers
-------------+------------------------+----------------------------------------------------
id | integer | not null default nextval('posts_id_seq'::regclass)
title | character varying(100) | not null
content | character varying(500) | not null
created_at | date |
updated_at | date |
tags | character varying(55) | not null default '50'::character varying
category_id | integer | not null default 1
Indexes:
"posts_pkey" PRIMARY KEY, btree (id)
comments table
Table "public.comments"
Column | Type | Modifiers
------------+------------------------+-------------------------------------------------------
id | integer | not null default nextval('comments_id_seq'::regclass)
post_id | integer | not null
name | character varying(255) | not null
email | character varying(255) | not null
content | character varying(500) | not null
created_at | date |
updated_at | date |
Indexes:
"comments_pkey" PRIMARY KEY, btree (id)
I’m trying to make a equivalent rails 3 sql statement of this.
select posts.id, posts.title
from posts
inner join (select distinct post_id,created_at
from comments
order by created_at DESC limit 5
) as foo
on posts.id=foo.post_id
order by foo.created_at DESC;
It’s to get recent commented-post (limit 5). It’s a complex sql query. Need to select posts.title from posts table joining comments table.
The Rails3 way to do a query like that is
find_by_sql:You could use
joinsif you wanted but, IMHO, that would just obfuscate things:Or perhaps something even more complicated like this:
Some things are just easier and clearer in SQL than AREL. The
find_by_sqlmethod exists for a reason:and this sort of thing is exactly what
find_by_sqlis for. You’ll have to pull outfind_by_sqlfor a lot of advanced SQL features (such as CTEs) and there’s no reason to be afraid of it or avoid it: ActiveRecord is a tool, not a dogmatic way of life.find_by_sqldoes have downsides (such as not playing that nicely with scopes) but so does the standard AREL stuff (such as not playing nicely with non-trivial SQL).