11

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!

4

3 回答 3

19

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.

于 2013-04-03T16:00:06.677 回答
2

Try using:

Photo.per_page = 2
Photo.page(params[:page]).order("date DESC")
于 2013-03-31T16:13:55.873 回答
1

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.

于 2013-04-03T05:02:48.063 回答