Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql Rails 3:对属于\u的对象进行排序_Mysql_Ruby On Rails 3 - Fatal编程技术网

Mysql Rails 3:对属于\u的对象进行排序

Mysql Rails 3:对属于\u的对象进行排序,mysql,ruby-on-rails-3,Mysql,Ruby On Rails 3,在我的网站上,每个帖子都有很多评论。用户可以通过多种方式对评论进行排序,尽管我可以使用sort!,我确信有一种方法可以使用MySQL查询来实现这一点。不幸的是,当我尝试以下方法时,注释返回未排序: @post.comments.order('created_at DESC') 我也试过: Comment.where("post_id = ?", @post.id).order('created_at DESC') 虽然我得到了同样的未分类的结果。我还可以如何处理这个问题?您可以尝试一下,看看

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

@post.comments.order('created_at DESC')
我也试过:

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

虽然我得到了同样的未分类的结果。我还可以如何处理这个问题?

您可以尝试一下,看看它是否有效!。。我相信可能会有更有效的方法,但不管怎样,这都会奏效

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

希望这对你有用

使用mysql
date
time
函数可能会有所帮助。我没有尝试下面的代码片段,但在
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。我建议创建一个
范围

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

无论哪个听起来更好:)

是的,这肯定有效。我现在用sort!得到了类似的结果!。不过,我更喜欢MySQL进行排序,因为它比Ruby快得多。一定有办法让它发挥作用。如果我发现了什么,我会告诉你的。我不明白为什么,但是MySQL方法都不起作用。不过这些应该有用,对吧?这意味着肯定还有其他问题。目前,我可以通过使用sort!获得我想要的结果!,但是我很困惑,为什么我不能通过数据库进行排序。你能添加几个示例行和你正在运行的命令吗。同时尝试从日志中添加代码段。这可能会有帮助。
Comment.where("post_id = ?", @post.id).latest_first #OR
Comment.latest_first.where("post_id = ?", @post.id)