Reputation: 969
I have a Ruby on Rails app with a Customer model that needs a related city/state. Adding a string column for the state could cause my coworkers to miss-type the location and I would have a harder time finding all the customers in a given city. Creating a model for a city that would only include a name seems excessive.
What is the correct way of storing this so that I can find my customers by city later on?
Upvotes: 0
Views: 631
Reputation: 16
You don't say why you need this info, but (assuming this is US city/state) storing a ZIP code is more accurate - "city" + "state" is not guaranteed to be unique.
Upvotes: 0
Reputation: 32170
If misstyping is a problem, keep the column as text, but have it as a select
instead of an input
tag.
You can also validate that column to see it matches the list of states
For the list you can have it in a constant to keep it accessible like
class User
STATES = Array[ ["AK", "Alaska"],
["AL", "Alabama"],
["AR", "Arkansas"],
["AS", "American Samoa"],
["AZ", "Arizona"],
["CA", "California"],
["CO", "Colorado"],
["CT", "Connecticut"],
["DC", "District of Columbia"],
["DE", "Delaware"],
["FL", "Florida"],
["GA", "Georgia"],
["GU", "Guam"],
["HI", "Hawaii"],
["IA", "Iowa"],
["ID", "Idaho"],
["IL", "Illinois"],
["IN", "Indiana"],
["KS", "Kansas"],
["KY", "Kentucky"],
["LA", "Louisiana"],
["MA", "Massachusetts"],
["MD", "Maryland"],
["ME", "Maine"],
["MI", "Michigan"],
["MN", "Minnesota"],
["MO", "Missouri"],
["MS", "Mississippi"],
["MT", "Montana"],
["NC", "North Carolina"],
["ND", "North Dakota"],
["NE", "Nebraska"],
["NH", "New Hampshire"],
["NJ", "New Jersey"],
["NM", "New Mexico"],
["NV", "Nevada"],
["NY", "New York"],
["OH", "Ohio"],
["OK", "Oklahoma"],
["OR", "Oregon"],
["PA", "Pennsylvania"],
["PR", "Puerto Rico"],
["RI", "Rhode Island"],
["SC", "South Carolina"],
["SD", "South Dakota"],
["TN", "Tennessee"],
["TX", "Texas"],
["UT", "Utah"],
["VA", "Virginia"],
["VI", "Virgin Islands"],
["VT", "Vermont"],
["WA", "Washington"],
["WI", "Wisconsin"],
["WV", "West Virginia"],
["WY", "Wyoming"] ]
...
end
and then access it via User::STATES
Upvotes: 3