Rails / Kaminari - How to order a paginated array?

2019-07-29 04:09发布

问题:

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.

回答1:

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)