Almost every website I have worked on has a form that asks for the user’s city and state. It’s a simple thing, omnipresent in almost any website, but oddly there’s no library to deal with that.
Maybe it’s a regional need, specific to my country, IDK, I just know that is very usual to my clients to require this information. So, in my day-to-day programmer’s life, I had to copy-and-paste snippets with the full list of states and cities.
In my projects I had to do something like this:
Of course I use a list of states of my own country.
I have to do the same thing for cities (actually I use a YAML file for the cities), which isn’t a very neat solution – hard coding your data is never a neat solution. Actually, it is even worse, because new cities are created every month in my country (so, the city list can be easily outdated), and also it limits the options for my country.
Looking for better solutions, I found this Carmen Gem, which provides a list of states from virtually every country in the world, but unfortunately, it doesn’t provide a list of cities. Also, it has a big and frightening warning that the gem is outdated.
To solve this problem, I created a gem called city-state. This gem provides an easy way to get a list of states from a country, and also a list of cities from a state. It also has an auto-update mechanism that avoids me to have to update the gem from time to time with new databases. This gem uses the MaxMind database, a very popular database used in many websites – mainly with the purpose of discovering the IP localization – and it’s updated weekly.
Updating the database from the internet:
How to use it in a form?
Let’s say that you have a form and want that your user picks a state and a city. Usually, you have a form like this:
With CityState gem, change your code to this:
How to build a city list after the user has picked a state?
To do this you will need to use Ajax: