我如何加入派生表?
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表加入posts表?
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)
评论
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
问题作者需要在跳转到SQL之前阅读基本的Rails和activerecord用法。 需要了解Activerecord如何为您的数据建模以及如何使用它。 首先找出你想用通用语言做什么,然后看看如何使用现有的做法。
Rails不知道你的@temp表的结构。 它只有一个结果集,据我所知,AREL不会从结果集中构建逻辑。 它从模式构建,它为活动记录模型提供了它。
您无法从此数据构建视图,因此您唯一的选择是使用带有activerecord类的标准连接选项或执行自定义sql。
在Rails 3中,ActiveRecord关系代数非常先进,使查询变得非常简单。
Comment.order("#{Comment.table_name}.created_at desc').limit(5).joins(:posts).order("#{Post.table_name} created_at desc")
- PG ::错误:错误:编码“UTF8”的无效字节序列:0xfc
- SQLite到Postgres(Heroku)GROUP BY
- 使用pg_search gem for substring在轨道上进行PG全文搜索
- 当ID存在时,获取“表的未知主键”
- 模型属性不会更新,在不更新的单独属性上调用validation错误?
- Rails 4 / postgresql index – 我应该使用一个datetime列作为索引filter,它可以有无限数量的值吗?
- 在多服务器环境中,如果站点的不活动超过15分钟,则服务器将失去与PostgreSQL数据库的连接
- 在Rails 5.0.0.beta3,-api选项中使用accepts_nested_attributes_for时出现问题
- ActionView :: Template :: Error(PG :: UndefinedFunction:ERROR:运算符不存在:整数~~未知