How do I arrange data in alphabetic order?

10 views
Skip to first unread message

Dave

unread,
Oct 3, 2006, 6:25:32 PM10/3/06
to rubyonra...@googlegroups.com
Okay, here's my question. I have data in a MySQL table and I want to
display the data in the alphabetical order of each row's title. Right
now it displays it in the order it's added. Is there a simple method I
can add to make it switch to alphabetical order, similar to how the
.reverse method? I'm really new, so this might not make sense...

Here's the code as I have it now in my list.rhtml:

<table>
<% for recipe in @recipes %>
<tr>
<td><h3><%= link_to h(recipe.title), :action => 'show', :id =>
recipe %></h3>
<p><%= h(recipe.description) %></p>
</td>
<td>
<%= link_to 'Edit', :action => 'edit', :id => recipe %><br />
<%= link_to 'Delete', :action => 'destroy', :id => recipe %>
</td>
</tr>
<% end %>
</table>

--
Posted via http://www.ruby-forum.com/.

Jon Garvin

unread,
Oct 3, 2006, 6:52:19 PM10/3/06
to rubyonra...@googlegroups.com
This should do it.

<% for recipe in @recipes.sort{|a,b| a.title <=> b.title } %>

Philip Hallstrom

unread,
Oct 3, 2006, 7:01:11 PM10/3/06
to rubyonra...@googlegroups.com
> Okay, here's my question. I have data in a MySQL table and I want to
> display the data in the alphabetical order of each row's title. Right
> now it displays it in the order it's added. Is there a simple method I
> can add to make it switch to alphabetical order, similar to how the
> .reverse method? I'm really new, so this might not make sense...

In your controller, change the line that looks like this:

@recipes = Recipe.find(:all, .....)

to include as an argument:

:order => 'title'

That should do it.

Vaibhav S.

unread,
Sep 25, 2014, 6:05:03 AM9/25/14
to rubyonra...@googlegroups.com
Jon Garvin wrote in post #148415:
> This should do it.
>
> <% for recipe in @recipes.sort{|a,b| a.title <=> b.title } %>

Jon Garvin .. you are awesome... I struggled the entire day yesterday
figuring out how to sort a dynamic list based on categories
alphabetically while working on creating a styleguide based on ruby. I
have no experience working on ruby. When i found this link via google i
finally got my Eureka Moment. Thanks once again for providing the code.

The magic code that helped me was .sort{|a,b| a<==>b}

just to provide the entire code in context i used is a below

<% for c in @categories.sort{|a,b| a <=> b} %>
<li><a href="<%= c[0] %>.html"><%= c[0] %></a></li>
<% end %>

i am wondering if i can use the same sorting filter in Jekyll...will
give a try.

thanks once again though
Reply all
Reply to author
Forward
0 new messages