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

百般思念 提交于 2019-12-03 03:36:47

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.

You can try jQuery plugin - bootstrap state picker

After including plugin inside your application

You can use it like this(example from http://bootstrapformhelpers.com/state):

<select id="countries_states1" class="form-control bfh-countries" data-country="US"></select>

<select class="form-control bfh-states" data-country="countries_states1"></select>

You can use country picker jQuery plugins of Bootstrap as following:

<select class="form-control bfh-countries" data-country="US"></select>

My recommendation is that unless you can be 100% certain the list is accurate and complete (and I'm skeptical that that is possible), don't do it.

I've registered on web sites in Singapore and other places where I had to select from a dropdown list of cities that did not include my town (and many other) correct towns (I live in the USA). I was forced to select an incorrect value pretty far away because the list was quite incomplete and it would not permit me to not select anything.

At the very least, if you want to provide choices, permit the user to enter a value not included in those choices.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!