<%= 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?
To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.
You can use the ASC and DESC keywords to specify ascending (smallest value first) or descending (largest value first) order. The default order is ascending. For DATE and DATETIME data types, smallest means earliest in time and largest means latest in time.
ASC: to sort the data in ascending order. DESC: to sort the data in descending order.
Like described on http://guides.rubyonrails.org/active_record_querying.html
@events.order(event_at: :desc)
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 %>
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.
Depending 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.
I 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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With