问题
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?
回答1:
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.
回答2:
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>
回答3:
You can use country picker jQuery plugins of Bootstrap as following:
<select class="form-control bfh-countries" data-country="US"></select>
回答4:
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.
来源:https://stackoverflow.com/questions/36736195/how-to-get-list-of-all-countries-and-cities-in-rails