Rails 3:订购Belongs_To的对象

时间:2012-09-03 00:26:32

标签: mysql ruby-on-rails-3

在我的网站上,每个帖子都有很多评论。用户可以通过多种方式对注释进行排序,虽然我可以使用sort来实现这一点!但我确定使用MySQL查询可以做到这一点。不幸的是,当我尝试以下方法时,注释返回未排序:

@post.comments.order('created_at DESC')

我也尝试过:

Comment.where("post_id = ?", @post.id).order('created_at DESC')

虽然我得到了相同的未分类结果。我怎么可能解决这个问题?

2 个答案:

答案 0 :(得分:0)

你可以尝试一下,看看它是否有效!我确定可能有更有效的方法来做到这一点,但无论如何都可以做到这一点

@post= @post.comments.sort_by(&:created_at)
@post = @post.reverse

希望这适合你!

答案 1 :(得分:0)

使用mysql datetime函数可能有所帮助。我没有尝试以下代码段,但date

会有点像这样
Comment.where("post_id = ?", @post.id, :order => 'date(created_at) DESC')

修改

尝试sqlite并且以下为我工作

Comment.where("post_id = ?", @post.id, :order => 'time(created_at) DESC')

同样的方法也适用于mysql。我建议创建一个scope喜欢

class Comment < AR::Base
     scope :latest_first, :order => 'time(created_at) DESC'
end

并像

一样使用它
Comment.where("post_id = ?", @post.id).latest_first #OR
Comment.latest_first.where("post_id = ?", @post.id)

对你来说哪个听起来更好:)