简体   繁体   中英

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!

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.

Try using:

Photo.per_page = 2
Photo.page(params[:page]).order("date DESC")

I was able to solve the problem after answering some other user's questions. After reviewing my "Photo" model, at the request of @mislav I realized that it contained:

default_scope :order => 'date'

After removing this default_scope, ordering started functioning properly as it should. Problem solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM