问题
The sql statement is like 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;
I want to get a rails 3 sql statement equivalent to the above one.
What i tried is given below:
The following sql query gives similar result.
select distinct post_id, created_at
from comments
order by created_at DESC limit 5
@temp = Comment.select('distinct(comments.post_id),created_at').order('created_at DESC').limit(5)
I tried to join this derived @temp table with posts table to get the posts.title
I tried this but failed.
@temp2 = @temp.joins('posts')
So, How can i join posts table with derived @temp 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 "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)
posts model, has_many :comments
, comments model, belongs_to :post
回答1:
Question author needs to read up on basic Rails and activerecord usage before jumping into SQL. Need to understand how Activerecord models your data and how to use it. First figure out what you want to do in common language and then see how you can use what exists to do it.
Rails does not know the structure of your @temp table. It only has a result set and from what I understand, AREL does not build logic from the result set. It builds from schemas which it pulls for active record models.
You cannot build a view from this data, so your only option is to use the standard join options with activerecord classes or to do custom sql.
In Rails 3, the ActiveRecord relational algebra is very advanced and has made queries very easy.
Comment.order("#{Comment.table_name}.created_at desc').limit(5).joins(:posts).order("#{Post.table_name} created_at desc")
来源:https://stackoverflow.com/questions/8403205/how-can-i-join-with-a-derived-table