2011-07-24 57 views
3

我正在使用rails gem kaminari(https://github.com/amatsuda/kaminari)爲了分頁我的帖子數據庫。目前我在我的控制器中有代碼@posts = Post.order('id').page(params[:page]).per(5),但是這個命令從最早到最近的頁面。我如何扭轉這種情況並從最近到最早訂購?分頁最近發佈的帖子與kaminari

回答

6
在模型

,你可以這樣做:

default_scope order("created_at DESC") 

default_scope order("created_at ASC") 
+0

我會縮短控制器代碼:'@posts = Post.page(PARAMS [:頁面] ).per(5)' – stephenmurdoch

+1

我可以做,而是'@posts = Post.order('created_at DESC')。page(params [:page])。per(5)'? – Vasseurth

+1

是的,這將是很好:) – stephenmurdoch

1
def index 
    @all = Model.all 
    @all = Model.order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page]) 
end 

def sort_column 
    Model.column_names.include?(params[:sort]) ? params[:sort] : "updated_at" 
end 

def sort_direction 
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "DESC/ASC" 
end