Zander Perry
Zander Perry

Reputation: 99

Rails / Kaminari - How to order a paginated array?

I'm having a problem ordering an array that I've successfully paginated with Kaminari.

In my controller I have:

@things = @friend_things + @user_things

@results = Kaminari.paginate_array(@things).page(params[:page]).per(20)

I want to have the final @results array ordered by :created_at, but have had no luck getting ordering to work with the generic array wrapper that Kaminari provides. Is there a way to set the order in the Kaminari wrapper? Otherwise what would be the best way? Thanks.

Upvotes: 2

Views: 3792

Answers (1)

Anezio Campos
Anezio Campos

Reputation: 1555

You could sort the elements before sending it to Kaminary, like this:

@things = @friend_things + @user_things
@things.sort! { |a,b| a.created_at <=> b.created_at }
@results = Kaminari.paginate_array(@things).page(params[:page]).per(20)

or

@things = @friend_things + @user_things
@things.sort_by! { |thing| thing.created_at }
@results = Kaminari.paginate_array(@things).page(params[:page]).per(20)

Upvotes: 6

Related Questions