2

@comments目前已排序 10 条记录id ASC
我想简单地颠倒顺序,所以我编码@comments = @comments.reverse

但我收到此错误消息

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

如果我取消反向并将其保留为@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
4

2 回答 2

5

你收到

ActionView::Template::Error (undefined method `total_count'

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

class Comment < ActiveRecord::Base
  scope :reversed, -> { order 'created_at DESC' }
end

然后通过调用范围来实例化您的评论:

@comments = Comment.reversed

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

Comment.reversed.where(:user_id => user_ids, :commentable_type => commentable)
于 2013-10-29T18:40:58.780 回答
1
@comments = Comment.where(:user_id => user_ids, :commetable_type => commentable).order("created_at DESC").page(params[:page]).per(10)

此外,您的页面计算错误可能会导致浮点数/小数。如果 params[:page] 为空,则默认为第一页的第 1 页。

于 2013-10-29T18:15:57.780 回答