Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort in .each loop in Rails 2.3

This is my code in the view. The Controller is simply getting the @category from the model.

This sort is not working. Ultimately I need it to sort alphabetically by name.

    <%- @category.brands.sort_by{|brand| brand.name}.each do |brand| -%>
    <li <%= "class='current'" if brand == @brand %>><%= link_to(brand.name, [@category, brand]) %></li>
<%- end -%>

Any ideas?

like image 923
TJ Sherrill Avatar asked Jul 21 '11 21:07

TJ Sherrill


2 Answers

I would use the sort function directly:

 <% @category.brands.sort { |a,b| a.name <=> b.name }.each do |brand| %>
   <li <%= "class='current'" if brand == @brand %>>
     <%= link_to(brand.name, [@category, brand]) %>
   </li>
 <% end %>
like image 105
ghayes Avatar answered Nov 06 '22 10:11

ghayes


If you commonly sort by the same field You can define the <=> method ( and optionally include Comparable ) on the model and just call model.sort and it should work.

in the model:

class Brand < AcvtiveRecord::Base
  def <=> other
    self.name <=> other.name 
  end
end

the view:

<% @category.brands.sort.each do |brand| %>
<li <%= "class='current'" if brand == @brand %>>
  <%= link_to(brand.name, [@category, brand]) %>
</li>
<% end %>

If it wasn't an association I would sort it in the controller or have the model return it sorted then just display it with the view.

Then in the controller ( if this was not a subcollection )

  @brands = Brand.all.sort

the view:

<% @brands.each do |brand| %>
<li <%= "class='current'" if brand == @brand %>>
  <%= link_to(brand.name, [@category, brand]) %>
</li>
<% end %>
like image 29
loosecannon Avatar answered Nov 06 '22 10:11

loosecannon