Mongoid Rails 4 sort by asc or desc order created_at

Chleo picture Chleo · Jun 4, 2014 · Viewed 27.3k times · Source

I have a rails 4 app using Mongoid. I want to do something basic is display the book model I have by descending order according to the field created_at in the index view. In the controller books_controller.rb:

def index
  @books = Book.order_by(:created_at.desc)
end

This is not working. I also tried the following 2 that are not working:

@books = Book.find :all, :order => "created_at DESC"

Book.find(:all, :order => "created_at DESC").each do |item|
  @books << item
end

In the view i have something like this:

<% @books.each do |b| %>
  ...
<% end %>

Thank you.

Answer

Shahzad Tariq picture Shahzad Tariq · Jun 4, 2014

You can try this

def index
  @books = Book.order_by(created_at: :desc)
end

it works fine.