【发布时间】:2011-12-06 16:20:11
【问题描述】:
sql语句是这样的:
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;
我想得到一个与上面相同的rails 3 sql语句。
我尝试过的如下:
下面的 sql 查询给出了类似的结果。
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)
我尝试将这个派生的@temp 表与posts 表连接起来以获取posts.title
我试过了,但失败了。
@temp2 = @temp.joins('posts')
那么,我如何将帖子表与派生的@temp 表连接起来?
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)
cmets
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)
帖子模型,has_many :comments,cmets 模型,belongs_to :post
【问题讨论】:
-
在 rails 3 中不使用 find_by_sql 就没有任何选择吗?
标签: sql ruby-on-rails ruby-on-rails-3 postgresql ruby-on-rails-3.1