Search code examples
ruby-on-railsformsstates

Rails Form Field for Selecting a State


I'm creating a Payment Form where users have to enter their state

In my users model, I have a state attribute

I have a states array as follows

states = %w(AL AK AZ AR CA CO CT DC DE FL GA HI ID IL IN IA KS KY LA ME MA MI MN MO MS
MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VA VT WA WI WV WY)

I want to create a drop-down menu where users can select a state

I read the documentation, but am confused on how to implement it.

Would something like this work?

<%= select_tag(:state, options_for_select(states)) %>

The output should look like this

  AL
  AK
  ...
  WY

And you can select each of the options.


Solution

  • While I am not always a fan of just grabbing and installing gems, I have found the Better State Select gem to be handy in these scenarios. Mostly because I can't be bothered to keep arrays of states in multiple apps :)!

    Better State Select

    I ran your code just fine in one of my apps so I can't see an issue with what you have but wanted to offer the Better State Select gem suggestion simply because I've found it an easier way to manage things like states (and as we expand into Canadia, it already has their provinces, etc.).

    Anyway, your code seems fine/workable to me as is!