Beginner question about sort

Let’s say I have two models: location and employee

  • employee belongs_to locations
  • locations has_many employees

On a particular page of an app, I am looping through each location and
then showing employees from that location.

In the controller, I am doing a search on all locations and listing
them by location_id.

In the view, I am looping through each location, and showing the
employee details for that location. However, the employees being listed
need to be shown in alphabetical order, but are being shown ordered by
id.

Since I am not flat-out searching for the employees in the controller,
how do I perform a sort on the employees to get them to list
alphabetically?

Here is the code I am using to loop through the locations and
employees:

<% @locations.each do |loc| %> <% loc.employees.in_groups_of(5) do |emp| %> <% emp.compact.each do |member| %> <% end %> <% end %> <% end %>
<%= loc.name %>
<%= link_to(image_tag( member.img_sml, :alt => member.title, :class => "empimg", :size => "42x45" ), { :controller => "profile", :action => "show", :id => member.id } ) %>
<%= member.first_name %> <%= member.last_name %>

Thanks for your help,
Sarah

sarah_hutchinson wrote:

employees:
<%= link_to(image_tag( member.img_sml, :alt => member.title, :class
=> “empimg”, :size => “42x45” ), { :controller => “profile”,
:action => “show”,
:id => member.id } ) %>

<%= member.first_name %> <%= member.last_name %>
<% end %>

<% end %> <% end %>

Here’s one way:

<% loc.employees.sort_by {|x| x.last_name +
x.first_name}.in_groups_of(5) do |emp| %>

Or, in your Location model you can change do this:

has_many :employees, :order => “last_name, first_name”

There are many other ways to do it. These are just a couple off the top
of my head.

Jamey

Confidentiality Notice: This email message, including any attachments,
is for the sole use of the intended recipient(s) and may contain
confidential and/or privileged information. If you are not the intended
recipient(s), you are hereby notified that any dissemination,
unauthorized review, use, disclosure or distribution of this email and
any materials contained in any attachments is prohibited. If you receive
this message in error, or are not the intended recipient(s), please
immediately notify the sender by email and destroy all copies of the
original message, including attachments.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs