Reputation: 2653
I want to include country selection select box in my Rails web form. How is it possible in Ruby on Rails? My form is like this
<%= form_for :User, :url => {:action => :create } do |f| %>
<div class="field">
<%= f.label :select_countries %><br />
<%= f.select(:countries, country_list) %>
</div>
<%= f.submit "Create" %>
<% end %>
What can I include in place of country_list?
Upvotes: 0
Views: 4867
Reputation: 2653
<%= f.country_select :country, ["United States"] %>
It really works for country_select gem
Upvotes: 2
Reputation: 6728
My opinion is to seed the countries list in database.
Create a model country with field 'name'.
In app/models/country.rb
attr_accessible :name
Load the list of country from the YAML file and seed into the database.
In config/country.yml
-
name: India
name: Pakistan
name: Cuba
#add required country name
In db/seed.rb
COUNTRIES = YAML.load_file(Rails.root.join('config/country.yml'))
COUNTRIES.each do |country|
Country.create(country)
end
Run
rake db:seed
Add country_id field in your user model(Write a migration to add field).
In app/models/user.rb
class User < ActiveRecord::Base
#associate user with country
belongs_to :country
end
In your new user form add the below code.
<%= f.select :country_id, Country.all.collect { |country| [country.name, country.id] },
{ :prompt => "Select Country" } %>
Upvotes: 4
Reputation: 176412
Rails used to provide a country select feature in the past. The feature has been extracted out from core and it's now packaged into the country_select plugin.
Use the plugin to enable the feature.
Upvotes: 1