How can I sort options in a select box?

Pretty much a newbie here, looking for help on select boxes in forms…

Is there any way in the view to sort the options of a drop-down select
box?

My current code (within a larger _form.rhtml file) is:

Location <%= select 'asset', 'location_id', [["Select a Location", ""],["", ""]] + Location.find_all.collect { |l| [ l.name, l.id ] } %>

This starts the drop-down menu with a null option “Select a Location”
followed by a blank line null option. Then it grabs all the locations
out of a table linked like:

class Asset < ActiveRecord::Base
belongs_to :location, :foreign_key => “location_id”
end

Basically, it works, but it’s sorted by the id of the location. I’d
like to sort it in ascending order by the name of the location.

Thanks!

-Mason

<%= select ‘asset’, ‘location_id’, [[“Select a Location”, “”],["",
“”]] + Location.find(:all, :order => ‘name’).collect { |l| [ l.name,
l.id ] } %>

If this is just part of a form, have a look at form_for:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M000387

<% form_for :asset, @asset, :url => { :action => ‘edit’ } do |f| %>
<%= f.select :location_id, [[“Select a Location”, “”],["", “”]] +
Location.find(:all, :order => ‘name’).collect { |l| [ l.name, l.id ]
%>
<% end %>

-Jonathan.

Jonathan V. wrote:

<%= select ‘asset’, ‘location_id’, [[“Select a Location”, “”],["",
“”]] + Location.find(:all, :order => ‘name’).collect { |l| [ l.name,
l.id ] } %>

If this is just part of a form, have a look at form_for:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M000387

<% form_for :asset, @asset, :url => { :action => ‘edit’ } do |f| %>
<%= f.select :location_id, [[“Select a Location”, “”],["", “”]] +
Location.find(:all, :order => ‘name’).collect { |l| [ l.name, l.id ]
%>
<% end %>

-Jonathan.

Thanks Jonathan. That’s exactly what I was looking for.

I didn’t know you could interrupt the Location.find_all.collect thing
with options to the find method. Learn something new every day.

-Mason

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