How to get list of all countries and cities in rails?

user6175355 picture user6175355 · Apr 20, 2016 · Viewed 10.4k times · Source

Is there a country and city gem where user will be able to select a country and based on selected country he will select a city?

I get multiple solution but they all support states not cities

gem 'country_select'
gem 'countries'
gem 'carmen-rails'

I want a list of all countries on dropdown and when I select any country then all cities of country will appear in cities dropdown. Is this possible through any gem?

Answer

ndnenkov picture ndnenkov · Apr 28, 2016

Use the aptly named city-state gem.


As seen by the README, you can do:

CS.cities(state, country)

If you want all cities in a given country, regardless of state, you could do:

CS.states(country).keys.flat_map { |state| CS.cities(state, country) }

To list all countries:

CS.countries

The cool thing is that it uses data from MaxMind so you can be sure the list will be up to date. To refresh your list, you can run:

CS.update

The only drawback is that it requires rails (active support specifically) to run, but this isn't a problem in your case.