There's many sites that provide you country list in sql file, so you can import it to your database. I would like to introduce you ruby way to create country list for your drop down menu. Let's we start :
- gem install tzinfo
- ruby script/plugin install tzinfo_timezone
- Add the code below to your Application_helper.rb
def make_attributes(hsh)
unless hsh.nil?
output = ""
hsh.each
do key, val
output << "
#{key}=\"#{val}\""
end
end
output
end
def country_code_select(object, method, priority_countries=nil, options={},
html_options={})
countries =
[TZInfo::Country.all.collect{xx.name},
TZInfo::Country.all_codes].transpose.sort
if
priority_countries.nil?
output = select(object, method, countries, options,
html_options)
else
output = "< id="'#{object}_#{method}'"
name="'#{object}[#{method}]'#{make_attributes">\n"
if
options[:include_blank] == true
output <<
""
end
priority_countries.each do pc
if options[:selected] ==
pc[:code] or options[:selected] == pc[:name]
output <<
"#{pc[:name]}\n"
else
output <<
"#{pc[:name]}\n"
end
end
output <<
"----------------------------\n"
output <<
options_for_select(countries, options[:selected])
output <<
"< / select >\n"
end
output
end
- Add this code to your view :
<%= country_code_select(:order, :ship_to_country,
priority_countries=[{:code=>'US',:name=>'United
States'}],{:selected=>'DK',:include_blank=>true},{:style=>'border:10px
solid red;'}) %>
Good Luck
.
1 Response to "Create Country List for Your Ruby on Rails Quickly"
The code has a few bugs. Fix below. You will have to delete spaces between '<' and 'select' for it to work as well as the last < / select >
def make_attributes(hsh)
unless hsh.nil?
output = ""
hsh.each {|key, val| output << "#{key}=\"#{val}\""}
end
output
end
def country_code_select(object, method, priority_countries=nil, options={}, html_options={})
countries = [TZInfo::Country.all.collect{|name| name}, TZInfo::Country.all_codes].transpose.sort
if priority_countries.nil?
output = select(object, method, countries, options, html_options)
else
output = "< select id='#{object}_#{method}' name='#{object}[#{method}]' #{make_attributes(html_options)}>\n"
output << "" if options[:include_blank] == true
priority_countries.each do |pc|
if options[:selected] == pc[:code] or options[:selected] == pc[:name]
output << "#{pc[:name]}\n"
else
output << "#{pc[:name]}\n"
end
end
output << "----------------------------\n"
output << options_for_select(countries, options[:selected])
output << "< / select >\n"
end
output
end
Post a Comment