'Adding scope to get objects in reverse order of their created time in rails

I'm new to Ruby on rails and programming. I am working on a exercise where I have a Post model,and I need to add a new scope to it to retrieve its objects in reverse order of their created time.

Here is my model code:

class Post < ActiveRecord::Base
      has_many :comments
      belongs_to :user 
scope :ordered_by_reverse_order, -> { order('created_at DESC').reverse} 
end

I have tried {reverse('created_at DESC')} as well, both didn't work.



Solution 1:[1]

Try this:

scope :ordered_by_reverse_order, -> { order('created_at ASC') }

Solution 2:[2]

Sounds like you want reverse_order (Rails 3+).

scope :ordered_by_reverse_order, -> { order(:created_at).reverse_order }

Solution 3:[3]

I prefer to use class methods when defining scopes for models on rails. This is the exact same as your scope method, but personally I think its cleaner.

Try ordering your posts in ascending order instead of descending:

class Post < ActiveRecord::Base
  has_many :comments
  belongs_to :user 

  def self.reversed
    order('created_at ASC')
  end 
end

# ASC
# Fri, 20 Feb 2015 08:41:26 UTC +00:00
# Fri, 20 Feb 2015 08:42:25 UTC +00:00
# Fri, 20 Feb 2015 08:43:53 UTC +00:00

# DESC
# Fri, 20 Feb 2015 12:43:25 UTC +00:00
# Fri, 20 Feb 2015 08:44:48 UTC +00:00
# Fri, 20 Feb 2015 08:43:53 UTC +00:00

Executing following command should return what you want:

Post.reversed

Solution 4:[4]

You could also just sort by DESC instead of using .reverse_order like this:

default_scope { order(created_at: :desc) }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan Rubio
Solution 2 messanjah
Solution 3 Jens
Solution 4 Lee McAlilly