5

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?

TJ Sherrill
  • 2,465
  • 7
  • 50
  • 88

2 Answers2

10

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 %>
hayesgm
  • 8,678
  • 1
  • 38
  • 40
1

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 %>
loosecannon
  • 7,683
  • 3
  • 32
  • 43
  • 1
    This is more "correct" than ghayes's method but will work about the same. Could do a hybrid of the approaches and just call sort with arguments in the controller, rather than defining the spaceship operator, if you aren't going to do this anywhere else. – Karl Jul 22 '11 at 01:58
  • haha the spaceship operator? I've never heard it referred to as sucht. I like it. – loosecannon Jul 22 '11 at 03:33