11

I have following data in database:

1
2
3
4
5

And I would like to get to output this:

3
4
5

I need it to print in the view:

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

I know that exists reverse_order, but exist something like reverse sort?

(I know that is possible to load the data into an array and then go through the array, but this way is not very efficient)

3 Answers 3

22

How about just doing

<%car.colors.limit(3).order('created_at DESC').reverse.each do |color|%>
Sign up to request clarification or add additional context in comments.

3 Comments

Would the anonymous downvoter like to tell me what I've got wrong?
This method reverses the data after it has been retrieve from the database. The answer from JellicleCat uses the database to sort it.
@MattScilipoti - but it gives the wrong answer. The OP wants (the first three in descending order), printed in ascending order. You'll note that I also use the database to perform the descending order, but I can't see how to use the DB to get it back into ascending order for display.
21

For Rails 4:

[Model].order(column: :desc)

For Rails 3:

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

For Rails 2:

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

Comments

0

One line Solution

in your controller use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.