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?
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 %>
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With