views:

41

answers:

3
<%= 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?

A: 

This should do it =

@events.sort {|a,b| b <=> a}

You can also see the sort documentation on Enumerables.

Damien MATHIEU
Sorry but im a newbie on ruby and rails. Whats does a, b stand for? Can you write an example with real names? Preferably with events_at
Emil
a and b are two elements of the array. You specify you want the second one before the first one.
Damien MATHIEU
Your example should be: <%= render :partial => 'event', :collection => @events.sort{|a,b| b.event_at <=> a.event_at } %>
Yannis
undefined method `desc' for #<WillPaginate::Collection:0xb5dac298>
Emil
<%= render :partial => 'event', :collection => @events.sort{|a,b| b.event_at <=> a.event_at } %> This example worked also. Thanks..
Emil
+1  A: 

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 %>
Yannis
Im using rails 2.3.5 :(
Emil
Then no problem, just adapt my example: `named_scope :desc, :order => ("events.event_at DESC")` and `<%= render :partial => 'event', :collection => @events.desc %>`
Yannis
I got an error mess when trying this. In event.rb in models i wrote named_scope :desc, :order => ("events.event_at DESC") and then tried to call it with <%= render :partial => 'event', :collection => @events.desc %> but i got the error mess: undefined method `desc' for #<WillPaginate::Collection:0xb5dac298>
Emil
You should hand the correctly sorted set to will-paginate. Or do something like `Event.paginate :page => params[:page], :order => 'created_at DESC'`
nathanvda
I do not quite understand your answer can you elaborate? What does 'the correctly sorted set to will-paginate' mean?
Emil
My mistake: it should have been: `<%= render :partial => 'event', :collection => Event.all.desc %>`. Whatever, if you're using will_paginate, do as nathanvda says (Depending on the version of will_paginate you're using, I think you can do `@events = Event.desc.paginate :page => params[:page]` with the desc named_scope).
Yannis
Emil
A: 

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.

Shadwell
This made it work. But i want to try out the other examples for learning.
Emil