Paginate by most recent post with kaminari
-
25-10-2019 - |
Pergunta
I'm using the rails gem kaminari (https://github.com/amatsuda/kaminari) in order to paginate my posts database. Currently I have the code @posts = Post.order('id').page(params[:page]).per(5)
in my controller, but this orders the pages from earliest to most recent. How do I reverse this and order from most recent to earliest?
Solução
in your model you can do:
default_scope order("created_at DESC")
or
default_scope order("created_at ASC")
Outras dicas
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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow