Satchel
Satchel

Reputation: 16724

How do I sort the outcome of my for-loop in ruby on rails

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?

Upvotes: 1

Views: 1759

Answers (2)

markgx
markgx

Reputation: 16

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

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

Upvotes: 0

Anurag
Anurag

Reputation: 141859

You could sort the emails before displaying them as:

<%
    sortedEmails = @campaign.emails.sort { |a, b| a.days <=> b.days }
    for email in sortedEmails
%>
...
<% end %>

Upvotes: 3

Related Questions