Follow Along as I Stumble on the Path to Learning RoR

Posts tagged “select

Select Drop Down in Simple_Form and Rails

I’m using the simple_form gem for forms in Rails and I needed to create a select (drop down) for a field.  In my case, it was for selecting US States, but this can be changed easily to whatever options you want to present by changing the options in the list.

In my user.rb model, I put the options (change these if your select is for something else than US States).

STATES =
[
[‘Alabama’, ‘AL’],
[‘Alaska’, ‘AK’],
[‘Arizona’, ‘AZ’],
[‘Arkansas’, ‘AR’],
[‘California’, ‘CA’],
[‘Colorado’, ‘CO’],
[‘Connecticut’, ‘CT’],
[‘Delaware’, ‘DE’],
[‘District of Columbia’, ‘DC’],
[‘Florida’, ‘FL’],
[‘Georgia’, ‘GA’],
[‘Hawaii’, ‘HI’],
[‘Idaho’, ‘ID’],
[‘Illinois’, ‘IL’],
[‘Indiana’, ‘IN’],
[‘Iowa’, ‘IA’],
[‘Kansas’, ‘KS’],
[‘Kentucky’, ‘KY’],
[‘Louisiana’, ‘LA’],
[‘Maine’, ‘ME’],
[‘Maryland’, ‘MD’],
[‘Massachusetts’, ‘MA’],
[‘Michigan’, ‘MI’],
[‘Minnesota’, ‘MN’],
[‘Mississippi’, ‘MS’],
[‘Missouri’, ‘MO’],
[‘Montana’, ‘MT’],
[‘Nebraska’, ‘NE’],
[‘Nevada’, ‘NV’],
[‘New Hampshire’, ‘NH’],
[‘New Jersey’, ‘NJ’],
[‘New Mexico’, ‘NM’],
[‘New York’, ‘NY’],
[‘North Carolina’, ‘NC’],
[‘North Dakota’, ‘ND’],
[‘Ohio’, ‘OH’],
[‘Oklahoma’, ‘OK’],
[‘Oregon’, ‘OR’],
[‘Pennsylvania’, ‘PA’],
[‘Puerto Rico’, ‘PR’],
[‘Rhode Island’, ‘RI’],
[‘South Carolina’, ‘SC’],
[‘South Dakota’, ‘SD’],
[‘Tennessee’, ‘TN’],
[‘Texas’, ‘TX’],
[‘Utah’, ‘UT’],
[‘Vermont’, ‘VT’],
[‘Virginia’, ‘VA’],
[‘Washington’, ‘WA’],
[‘West Virginia’, ‘WV’],
[‘Wisconsin’, ‘WI’],
[‘Wyoming’, ‘WY’]
]

Now in my simple_form, I put this:

<%= simple_form_for(@user) do |f| %>
<%= f.input :indiv_state, collection: User::STATES %>
<%= f.button :submit %>
<% end %>


ActiveAdmin: Turning Hashes/ActiveRecord Hashes to Field Values

After I installed ActiveAdmin gem, everything worked great except I had an issue where the dropdown menus were showing ActiveRecord hashes like this:

#<Category:0x698a648>

Instead of showing a name like the other fields.  It seems that the default is to show a field called “name” in the dropdown menus in ActiveAdmin, and if you don’t have such a field it shows the ActiveRecord instead.  Changing that was easy, after I found this StackOverflow question.

All you have to do is go into the model and add a method for to_s, like this:

def to_s
# field name you want to show in the drop down
end

for me, I put:

def to_s
id
end


Select Default

To have a default value above the options in a Rails select box, use :prompt.

ie

<%= f.select(:field_name, {“option1″=>”option1″ ,”option2″ =>”option2″}, :prompt=>”Please select an option”) %>