parameter
parameter

Reputation: 904

issue with pagination when sorting using 'sort_by'

I get this error from the will paginate gem: undefined methodtotal_pages' for Array:0xa2710a0`

When I try to paginate in my artist controller after using 'sort_by' rather 'order'. Does anyone know of a way around this? It seems you can't use paginate in this way because @artists becomes an array rather than an active record collection? Any suggestions are appreciated

to clarify i'm using sort_by rather than .order for these 3 parameters because they're calls to functions within my model, not columns in my Artist database table.

def index
    if params[:search]
        @artists = Artist.search(params[:search].titleize).paginate(:page => params[:page]).order("created_at DESC")
    elsif params[:sort] == "numConcerts"
        @artists = Artist.all.paginate(:page => params[:page]).sort_by{|artist| artist.concerts.size}.reverse
    elsif params[:sort] == "avgRating"
        @artists = Artist.all.paginate(:page => params[:page]).sort_by{|artist| artist.avgOverall}.reverse
    elsif params[:sort] == "numReviews"
        @artists = Artist.all.paginate(:page => params[:page]).sort_by{|artist| artist.numReviews}.reverse
    else
        @artists = Artist.paginate(:page => params[:page]).order(:name)
    end
  end

the code in the view is just

<%= will_paginate @artists %>

edit: this seems to be the same issue i'm having, it's from 2008 but i'm going to try: http://pathfindersoftware.com/2008/06/how-to-use-will_paginate-with-non-activerecord-collectionarray/

edit 2: nope couldn't get it to work still

edit 3: tried doing 'require 'will_paginate/array'' but that didn't do fix it.

Upvotes: 1

Views: 1132

Answers (1)

parameter
parameter

Reputation: 904

after much struggling I decided to switch to kaminari which works exactly the same but has better integration for handling arrays it seems. I simple did this and it worked.

def index
    if params[:search]
        @artists = Artist.search(params[:search].titleize).order("created_at DESC").page(params[:page])
    elsif params[:sort] == "numConcerts"
        @artists = Kaminari.paginate_array(Artist.all.sort_by{|artist| artist.concerts.size}.reverse).page(params[:page]).per(15)
    elsif params[:sort] == "avgRating"
        @artists = Kaminari.paginate_array(Artist.all.sort_by{|artist| artist.avgOverall}.reverse).page(params[:page]).per(15)
    elsif params[:sort] == "numReviews"
        @artists = Kaminari.paginate_array(Artist.all.sort_by{|artist| artist.numReviews}.reverse).page(params[:page]).per(15)
    else
        @artists = Artist.order(:name).page(params[:page])
    end
end

Upvotes: 2

Related Questions