如何对按日期时间排序的记录进行排序?

MKK*_*MKK 2 ruby-on-rails ruby-on-rails-3

@comments共有10条记录,id ASC现在排序.
我想简单地改变订单,所以我编码了@comments = @comments.reverse

但我收到此错误消息

ActionView::Template::Error (undefined method `total_count'
<%= page_entries_info(@comments, :entry_name => 'comment').html_safe %>
Run Code Online (Sandbox Code Playgroud)

如果我倒退并保持原样@comments = @comments,那就不会有任何问题.为什么?我如何按顺序排序created_at DESC

@comments = Comment.where(:user_id => user_ids, :commentable_type => commentable)

if params[:page].blank?
    params[:page] = ((@comments.count - 1)/10) + 1
    @comments = @comments.page(params[:page]).per(10)
else
    @comments = @comments.page(params[:page]).per(10)
end

@comments = @comments.reverse
Run Code Online (Sandbox Code Playgroud)

Die*_*zar 5

你收到了

ActionView::Template::Error (undefined method `total_count'
Run Code Online (Sandbox Code Playgroud)

因为@comments.reverse返回一个普通的数组.您需要具有分页功能的Relation对象.完成排序需求的最佳方法是在注释模型中创建范围:

class Comment < ActiveRecord::Base
  scope :reversed, -> { order 'created_at DESC' }
end
Run Code Online (Sandbox Code Playgroud)

然后通过调用范围来实例化您的注释:

@comments = Comment.reversed
Run Code Online (Sandbox Code Playgroud)

您可以page在该@comments集合上调用该方法,其余的应该可以正常工作.你可以where像以前一样把它链起来,所以它看起来像:

Comment.reversed.where(:user_id => user_ids, :commentable_type => commentable)
Run Code Online (Sandbox Code Playgroud)