Rails Kaminari - How to order/paginate arrays?

gerky picture gerky · Aug 5, 2012 · Viewed 7.5k times · Source

I'm following the railscast for Kaminari (http://railscasts.com/episodes/254-pagination-with-kaminari). But I'm stuck with the controller part.

In my controller, I have something like this:

def index
  @articles = (params[:mine] == "true") ? current_user.articles : Article.search(params[:search])

  respond_to do |format|
    format.html
    format.json { render json: @articles }
  end
end

And now I'm not sure how to chain the methods, order, page and per, like in the screencast .order("name").page(params[:page]).per(5). I keep on getting the no method 'order' in Array. I know I can't call the methods on arrays but how else can I chain them?

Answer

slhck picture slhck · Aug 5, 2012

You can use Kaminari on Arrays:

Kaminari.paginate_array(@articles).page(params[:page]).per(5)

From the documentation:

Kaminari provides an Array wrapper class that adapts a generic Array object to the paginate view helper. However, the paginate helper doesn’t automatically handle your Array object (this is intentional and by design). Kaminari::paginate_array method converts your Array object into a paginatable Array that accepts page method.