List alphabetically in Rails?

I have a selected list in my model that lists the names of people with their employers:

<li>Case Handler Name<span><%= f.select :person_id, Person.all.collect { |x| [x.name_and_company, x.id] } %></span></li> def name_and_company return "#{personname} (#{company})" end 

Can I force the selection list in alphabetical order?

I guess I would put an order tag there ... somewhere?

 (:order => 'personname DESC') 

Thanks,

Danny

+6
list select ruby-on-rails order
source share
3 answers

You can do it like this:

 # controller @people = Person.order_by('personname ASC').collect {|x| [x.name_and_company, x.id] } # model named_scope :order_by, lambda { |o| {:order => o} } # view <%= f.select :person_id, @people %> 
+10
source share

Answer:

  #users_controller.rb def index @people = Person.alphabetically end #user.rb scope :alphabetically, order("name ASC") #index.haml = f.select :person_id, @people.all.collect { |p| [p.name, p.id] } %> 
+8
source share

Even easier ...

 <%= f.select :name, options_from_collection_for_select(Person.order("name ASC"), :name, :name), :prompt => 'Select' %> 

Note. It does not require custom methods or additions to the controller.

+4
source share

All Articles