Order a collection as DESC
Matthew Martinez
<%= render :partial => 'event', :collection => @events.sort_by(&:event_at)%>This code shows a collection ordered as ASC, but i want to order this collection as DESC.
How can I achieve this?
8 Answers
Like described on
@events.order(event_at: :desc) 2 Even better, you can set a scope to sort your event and use it in your render.
In your Event model:
scope :desc, order("events.event_at DESC")If you use Rails3, in your view you can simply do:
<%= render @events.desc %> 6 In Rails 3 the correct syntax is:
<%= render :partial => 'event', :collection => @events.order(:event_at).reverse_order %> You can just reverse the sorted collection:
<%= render :partial => 'event', :collection => @events.sort_by(&:event_at).reverse %>but as Yannis says you are better off sorting as you fetch things from the database ideally.
3Depending of the kind of object you have, you will have different ways of doing the sort function.
If your object is an ActiveRecord, you can do it the following way:
@events.order('events.event_at DESC')This will add an ORDER clause to your SQL query, sorting the entries before you retrieve them from the database.
The second solution is slower, as you're sorting your entries in ruby.
But if you're manipulating an array of objects, it's your only solution.
@events.sort {|a,b| b.event_at <=> a.event_at }This will loop through all the events, checking each one of them for the biggest one with the <=> method.
You can also see the sort documentation on Enumerables.
5I wanted to display a league table and order by points desc. After trying out several unsuccesful methods this is what worked for me in this instance. I added this line to my controllers index method.
@teams = Team.all.order(points: :desc) 1 You can do this by using desc method with parameter.
See below example
@events.desc(:event_at)This will give you @events in descending order of event_at field.
Thanks.
In views/sources/show.html.erb the following <%= render @source.docs.order(page_no: :asc) %> works in Rails 6.
This calls _doc.html.erb which contains
<li> <%= doc.content %> (p. <%= doc.page_no %>) <span><%= link_to 'Show', doc %></span> <span><%= link_to 'Edit', edit_doc_path(doc) %></span>
</li>Rails magic! An ordered list containing selected fields of docs that reference a source. And can click to edit or view the entire doc.
Thank you. One of the answers here pointed me in the sorting part.