Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make select list output in alphabetical order in Rails?

I have a select list in my model which lists a persons name with their employers name:

<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

Is it possible to force the select list to output in alphabetical order?

I am assuming I would put an order tag in there...somewhere?

(:order => 'personname DESC')

Thanks,

Danny

like image 669
dannymcc Avatar asked Aug 16 '10 19:08

dannymcc


Video Answer


2 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 %>
like image 101
Ju Nogueira Avatar answered Oct 26 '22 15:10

Ju Nogueira


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] } %>
like image 34
Victor Hazbun Anuff Avatar answered Oct 26 '22 14:10

Victor Hazbun Anuff