1

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-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.

1
  • version 2.3.8 I think. Def not 3 Commented Dec 27, 2010 at 0:21

2 Answers 2

5
@menu_bar.link_pages.sort_by { |e| e.sequence }.each do |lp|
  . . .
Sign up to request clarification or add additional context in comments.

1 Comment

@menu_bar.link_pages.sort_by &:sequence.each do |lp| is the shorthand to_proc way. See also this SO discussion
2

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| %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.