4
\$\begingroup\$

I was creating a Rails form where users have to enter their state. I ended up creating a select tag which is really, really ugly.

I'd like to think there's a better way of writing this.

<p>
        <%= f.label :state, "State:*" %></br>
          <%= f.select(:state, [['AL', 'AL'], ['AK', 'AK'], ['AZ', 'AZ'], ['AR', 'AR'], ['CA', 'CA'], ['CO', 'CO'], ['CT', 'CT'], ['DC', 'DC'], ['DE', 'DE'],
          ['FL', 'FL'], ['GA', 'GA'], ['HI', 'HI'], ['ID', 'ID'], ['IL', 'IL'], ['IN', 'IN'], ['IA', 'IA'], ['KS', 'KS'], ['KY', 'KY'], ['LA', 'LA'], ['ME', 'ME'],
          ['MD', 'MD'], ['MA', 'MA'], ['MI', 'MI'], ['MN', 'MN'], ['MS', 'MS'], ['MO', 'MO'], ['MT', 'MT'], ['NE', 'NE'], ['NV', 'NV'], ['NH', 'NH'], ['NJ', 'NJ'],
          ['NM', 'NM'], ['NC', 'NC'], ['ND', 'ND'], ['OH', 'OH'], ['OK', 'OK'], ['OR', 'OR'], ['PA', 'PA'], ['RI', 'RI'], ['SC', 'SC'], ['SD', 'SD'], ['TN', 'TN'],
          ['TX', 'TX'], ['UT', 'UT'], ['VT', 'VT'], ['VA', 'VA'], ['WA', 'WA'], ['WI', 'WI'], ['WV', 'WV'], ['WY', 'WY']]) %>
        </p>
\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

you should move the states list outside of view, i.e. to model class.

class User < ActiveRecord::Base
  STATES = ['AL', 'AK', 'ID']
end

then in view:

<%= f.label(:state, "State:*") %></br>
<%= f.select(:state, User::STATES) %></br>

This will allow you to reuse states collection anywhere across the application and add easily validate if user hasn't modified the form manually.

Keeping states in User model is not necessary the best option but it's outside of this question scope

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Some details: 1) Be consistent with parens on the helper calls. 2) You can drop the options_for_select. \$\endgroup\$
    – tokland
    Commented Dec 6, 2014 at 10:14
1
\$\begingroup\$

Adding to what rui said, it is usually nicer to present well-formatted data to the user; in this case, "Florida" instead of "FL". Store your STATES as a hash, using Hash#values for the display and Hash#keys for the internal logic.

Also, considering using Symbols for the Hash keys

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.