Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Pagination: Sort order not respected (will_paginate gem)

Okay, I'm sure there's a simple solution to my problem. Here is my controller.rb code:

@photos = Photo.paginate :page=>params[:page], :order => "date DESC", :per_page => 2

For some reason, my sort order is not being respected. Pagination is functioning correctly (such as the number per page) but the order is not working at all. I've tried using different values like ASC and DESC as well as different fields to no avail. Here is my entire controller function after moving "order" first :

def index
  @photos = Photo.all
  @photos = Photo.order("date DESC").paginate(:per_page => 12, :page => params[:page])
  respond_to do |format|
    format.html # index.html.erb
    format.json { render :json => @gallery }
  end
end

I previously had this working perfectly in Rails 1, I just cannot figure this out with the will_paginate gem. As I mentioned, the :per_page parameter is working so I know the pagination is working, I'm just getting no sorting and no errors. I would appreciate any help!

like image 405
Cornelius Qualley Avatar asked Mar 31 '13 01:03

Cornelius Qualley


2 Answers

You have a default order (by means of default_scope) which you can't override with the order() method, only append more ordering rules. You can reset the order, however:

@photos = Photo.reorder("date DESC").page(params[:page]).per_page(12)

BTW, you'll want to remove the @photos = Photo.all from the controller action. If you're fetching a paginated set of photos, it doesn't make sense to fetch them all from database first.

like image 155
mislav Avatar answered Sep 29 '22 21:09

mislav


Try using:

Photo.per_page = 2
Photo.page(params[:page]).order("date DESC")
like image 41
Dave S. Avatar answered Sep 29 '22 21:09

Dave S.