Search code examples
ruby-on-railsrubyscopes

Scope ordering by reverse order not working


I have my scope:

scope :latest_photos, -> {order(:created_at).reverse_order.limit(10)}

It's supposed to put the latest photos in first place right? Well photos get put on the last place instead.

I've also tried:

scope :latest_photos, -> {order('created_at DESC').limit(10)} 

but nothing. Any ideas? Thanks!

EDIT

Something is not working here:

routes.rb

get 'spots/ultimos' => 'photos#latest

photos controller

def latest
        @categories = Category.all
        @zones = Zone.all
        @photos = Photo.latest_photos
        @action = 'general'
        @photos = Photo.paginate(:page => params[:page])
        render :index
    end

model

  scope :latest_photos, -> {order(created_at: :desc).limit(10)}

Solution

  • def latest
        @categories = Category.all
        @zones = Zone.all
        @photos = Photo.latest_photos
        @action = 'general'
        @photos = Photo.paginate(:page => params[:page])
        render :index
    end
    

    You have assigned @photos variable twice, second assignment overrides the previous one. Instead do:

    def latest
        @categories = Category.all
        @zones = Zone.all
        @photos = Photo.latest_photos
        @action = 'general'
        render :index
    end
    

    The actual value to be assigned depends on what you want to achieve here. Since action is called latest and you have limit in your scope, I have assumed you don't need pagination here.