What is the best way to sort an array of Active Record objects by by a field?
This array is a field of an object, link_pages
, and I want it sorted by the field "sequence
"
<% @menu_bar.link_pages.each do |lp| %>
<li id="page_<%= lp.id%>" class="ui-state-default">
<span class="ui开发者_如何学JAVA-icon ui-icon-arrowthick-2-n-s"></span>
<font size=5><%= lp.name %></font> |
<%= link_to "remove",
:controller => "admin/menu_bars",
:action => :remove_page_from_menu,
:page => lp.id,
:id => @menu_bar.id %>
</li>
<% end %>
Maybe there is a way to do @menu_bar.link_pages.sort_by_sequence.each do
, which would be slick, but I just don't know.
@menu_bar.link_pages.sort_by { |e| e.sequence }.each do |lp|
. . .
Is link_pages
really an array of activerecord objects?
What happens if you add this in the view?
<%= debug @menu_bar.link_pages.class %>
Two things can happen. It can print "Array" or it can print "ActiverecordThing" (something similar to that, definitively not Array).
If you really have an Array, use DigitalRoss' solution. If you have an "ActiverecordSomething", then, create a named_scope, so you can reuse easily:
# Assuming that your model name is "Page"
class Page < ActiveRecord::Base
...
named_scope :sorted_by_sequence, :order => 'pages.sequence ASC'
...
end
Then you can do:
<% @menu_bar.link_pages.sorted_by_sequence each do |lp| %>
精彩评论