HUSTEN
HUSTEN

Reputation: 5197

How can I order when using pagination?

This might be quite simple question.

Here's my code. Then I want to sort @codes ordered by the column code.user.last_active_at

#here, I retrieve only the records that contains particular keyword.
@search = Code.search do  
    fulltext params[:search]
    with(:community_id, community_search)
    paginate :page => 1, :per_page => 1000000
end  

#Here, I try pagination. 10 records per each page.  
@codes = @search.results
@codes = Kaminari.paginate_array(@codes).page(params[:page]).per(10)

I want to sort them ordered by the column @code.user.last_active_at
How can I do that?

I tried this

@codes = Kaminari.paginate_array(@codes.joins(:user).order('user.last_active_at DESC')).page(params[:page]).per(10)

But it returned this error

NoMethodError (undefined method `joins' for #
<Sunspot::Search::PaginatedCollection:0x0000001ca851a8>):
app/controllers/codes_controller.rb:95:in `index'

How can I sort while I'm using Kaminari pagination?

Upvotes: 1

Views: 480

Answers (1)

Adeptus
Adeptus

Reputation: 683

Kaminari not affect on sorting. first you have to sort and then get page(x).per(x) so for example in your controller

@codes = @search.results
@codes = @codes.joins(:user).order('user.last_active_at DESC').page(params[:page]).per(10)

edit: after check sunspot documentation I think you can make something like

@search = Code.search(include: :user) do  
    fulltext params[:search]
    with(:community_id, community_search)
    order_by('user.last_active_at DESC')
    #paginate :page => params[:page], :per_page => 10 you can add this and not use Kaminari
end  

you can try joins except include

Upvotes: 1

Related Questions