Rails 3限制正在搞乱数据库查询中的排序

时间:2012-07-11 20:14:03

标签: mysql ruby-on-rails-3 activerecord

我正在使用will_paginate gem和rails 3.2.3。 我试图显示所有帖子都有最新帖子订购的某些标签,所以我用它:

  @posts = Post.find_by_post_type_label(session[:current_post_type],@selected_labels)
             .paginate(:page => params[:page], :order => "comments.created_at DESC").all

但它不按顺序返回帖子。每个页面都将被排序,但第二页将包含应该在第一页上的帖子。

示例:

Post.find_by_post_type_label(1,[])

返回帖子[1,2,3,4,5,6,7,8,9,10],其中每个最新评论都是几个月前发布的。它生成的sql是:

 SELECT `posts`.* FROM `posts` WHERE `post`.`post_type_id` = 1

 SELECT `comments`.* FROM `comments` WHERE `comments`.`post_id` IN ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ) ORDER BY created_at DESC

如果我订购它,并限制它,例如:

Post.find_by_post_type_label(1,[]).order(comments.created_at DESC).limit(5)

这就是will_paginate的用法,它返回帖子2,3,4,5,7

生成后:

SELECT DISTINCT `post`.id FROM `posts` LEFT OUTER JOIN
`comments` ON `comments`.`post_id` = `post`.`id` WHERE 
`post`.`post_type_id` = 1 ORDER BY posts.created_at DESC LIMIT 5

 SELECT `post`.`id` AS t0_r0, `post`.`user_id` AS t0_r1, `post`.`name` AS 
 t0_r2, `post`.`image_id` AS t0_r3, `post`.`post_type_id` AS t0_r4, 
`post`.`description` AS t0_r5, `post`.`featured` AS t0_r6, `post`.`approved`
AS t0_r7, `comment`.`id` AS t1_r0, `comments`.`post_id` AS t1_r1, 
`comments`.`image_id` AS t1_r2, `comments`.`edits` AS t1_r3, 
`comments`.`color` AS t1_r4, `comments`.`min_reputation` AS t1_r5, 
`comments`.`created_at` AS t1_r6, `comments`.`updated_at` AS t1_r7 FROM 
`post` LEFT OUTER JOIN `comments` ON `comments`.`post_id` = 
`post`.`id` WHERE `post`.`post_type_id` = 1 AND `post`.`id` IN (2, 3, 
4, 5, 7) ORDER BY comments.created_at DESC

它在订购之前明显受到限制,但我无法弄清楚如何改变它。 任何帮助将不胜感激

编辑1

关系如下:

Class Post
  belongs_to :user
  belongs_to :post_type
  has_many :comments, dependent: :destroy, order: 'created_at DESC'
  has_and_belongs_to_many :labels

Class Comment
  belongs_to :post
  belongs_to :user

注释是数据库中唯一具有时间戳的注释。第一条评论保留了帖子的创建时间。

2 个答案:

答案 0 :(得分:1)

在find_by_sql

中使用此sql进行了编辑
SELECT  p1.*, iv.created_at FROM posts p1
INNER JOIN ( SELECT p2.id id, max(c.created_at) created_at FROM posts p2
            INNER JOIN comments c ON c.post_id = p2.id
            GROUP BY p2.id)
iv ON p1.id=iv.id ORDER BY iv.created_at DESC LIMIT 5

答案 1 :(得分:0)

您应该考虑方法find_by_sql

所以你可以像这样重写你的查询:

ts = Post.find_by_sql("SELECT * FROM posts WHERE post_type_id = ? and id in (?) ORDER BY created_at DESC LIMIT 5", session[:current_post_type], @selected_labels).paginate(:page => params[:page]).all

我不确定@selected_labels是什么,也是由Post.created_at排序而不是评论,我不知道你为什么要按评论对帖子进行排序...你想看到吗?最活跃的帖子呢?