views:

58

answers:

2

I have a loop as follows:

<% for email in @campaign.emails%>
    <strong>Email: </strong><%=h email.title %> sent after <%=h email.days %> days </br>
<% end %>

But actually I want it sorted by the email.days value when it displays to the screen.

How do I do that?

+2  A: 

You could sort the emails before displaying them as:

<%
    sortedEmails = @campaign.emails.sort { |a, b| a.days <=> b.days }
    for email in sortedEmails
%>
...
<% end %>
Anurag
mckeed
@mckeed, your take seems cleaner, is the outcome the same as the other approach?
Angela
@Angela: yes it is equivalent, though it will use a bit more memory and might take a little more time in this case. The difference is that `sort` evaluates the block every time it makes a comparison between two elements in the process of sorting, and `sort_by` first makes a parallel array by calling `.days` on each element and sorts the original array by sorting that one.
mckeed
ah, so the sort_by is what would take more time? The number of emails in a campaign won't be bigger than 50 so both are the same?
Angela
Where can I read up more on the different ways to pass query parameteres through rails?
Angela
A: 

If you're using ActiveRecord, you can do something like

<% for email in @campaign.emails.all(:order => "days") %>

markgx
Angela
The difference is that this approach makes the database do the sorting when it fetches the records, rather than fetching them and then sorting them with ruby. This way will be faster unless you have already fetched the emails during this request in which case this will make another database query.
mckeed
@mckeed, thanks for the info, getting the database to do the sorting is something I'd like to do. so it sounds like using :order => days is faster?
Angela