How to sort in .each loop in Rails 2.3

This is my view code. The controller simply gets @category from the model.

This view does not work. Ultimately, I need it to be sorted 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?

+5
source share
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 %>
+10
source

If you usually sort by the same field, you can define a method <=>(and optionally include Comparable) in the model and just call model.sortit and it should work.

in model:

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

view:

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

, , , .

( )

  @brands = Brand.all.sort

:

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

All Articles