patternrubyrailsMinor
Rendering a selection box for 50 states
Viewed 0 times
selectionstatesforrenderingbox
Problem
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.
I'd like to think there's a better way of writing this.
Solution
you should move the states list outside of view, i.e. to model class.
then in view:
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
class User < ActiveRecord::Base
STATES = ['AL', 'AK', 'ID']
endthen in view:
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
Code Snippets
class User < ActiveRecord::Base
STATES = ['AL', 'AK', 'ID']
end<%= f.label(:state, "State:*") %></br>
<%= f.select(:state, User::STATES) %></br>Context
StackExchange Code Review Q#71836, answer score: 5
Revisions (0)
No revisions yet.