Nicholas Alek
Nicholas Alek

Reputation: 273

Sorting alphabetically on select in rails using formtastic?

I have bunch of states I need to sort alphabetically in rails using formtastic. There is one small caveat. In the states table, I have a name for the state with 'N/A'. The 'N/A' has to come first the collection of all states using select form helper method. This is my code currently:

f.input :state, :as => :select, :collection => State.all,  :include _blank => false

How do I place the 'N/A' state name at the top of collection followed by the rest of states alphabetically? Example: 'N/A, Alabama, Alaska, etc....'.

Thanks to everyone for help/clues.

Upvotes: 3

Views: 1126

Answers (1)

vee
vee

Reputation: 38645

Try:

f.input :state, 
        :as => :select, 
        :collection => State.all.sort_by(&:name), 
        :prompt => 'N/A'

Using State.all.sort_by(&:name) to sort by the state name attribute, and using prompt: 'N/A' to show N/A as the first option in the select.

or, sort in the db using:

f.input :state, 
        :as => :select, 
        :collection => State.order(:name), 
        :prompt => 'N/A'

Upvotes: 5

Related Questions