Rails 3 - ActiveRecord and reverse sorting

I have the following data in the database:

1 2 3 4 5 

And I would like to get this:

 3 4 5 

I need this to print in a view:

 <%car.colors.limit(3).order('created_at ASC').each do |color|%> ... 

I know there is reverse_order , but is there something like reverse sort ?

(I know that you can load data into an array and then go through the array, but this method is not very efficient)

+8
sorting database mysql activerecord ruby-on-rails-3
source share
3 answers

How to just do

 <%car.colors.limit(3).order('created_at DESC').reverse.each do |color|%> 
+20
source share

For Rails 4:

 [Model].order(column: :desc) 

For Rails 3:

 [Model].order("<column> DESC") 

For Rails 2:

 [Model].all(:order => "<column> DESC") 
+18
source share

Single line solution

in your controller:

 class Api::ImagesController < ApplicationController def index @posts = Post.all.paginate(:page => params[:page], :per_page => 4).order(id: :desc) render :json => @posts.to_json(:methods => [:image_url]) end end 
0
source share

All Articles