2013-10-29 140 views
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 

回答

5

您收到

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

因为@comments.reverse返回一个普通的数组。你需要一个具有分页功能的关系对象。完成您的排序需求的最好方法是在你的意见模型来创建一个范围:通过调用范围

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) 
1
@comments = Comment.where(:user_id => user_ids, :commetable_type => commentable).order("created_at DESC").page(params[:page]).per(10) 

而且,你的页面计算是糟糕状况可能导致浮法/小数。如果params [:page]为空,则默认为第一页的第一页。

+0

这不是我不想要:(如果我这样做,第一页都将有最新帖子 – MKK

+0

你问我如何排序顺序由created_at desc。修改问题。你想要什么?最新的帖子按时间顺序排列或按id字段排列的最新帖子? – cpjolicoeur

+0

我希望它们在'同一'顺序但'DESC'顺序在同一页内。 – MKK