How do I arrange data in alphabetic order?

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:

<% for recipe in @recipes %> <% end %>

<%= link_to h(recipe.title), :action => 'show', :id => recipe %>

<%= h(recipe.description) %>

<%= link_to 'Edit', :action => 'edit', :id => recipe %>
<%= link_to 'Delete', :action => 'destroy', :id => recipe %>

This should do it.

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

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.

Jon G. wrote in post #148415:

This should do it.

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

Jon G. … 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} %>

  • <%= c[0] %>

  • <% end %>

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

    thanks once again though