Country list in YAML format, countries.yml

I made myself a list of countries in YAML format for use in a Rails app today.

Here it is: countries.yml

You can put this file into a directory called db/seed_data and then set up a rake task to load it into your database. Put this into the file seed_data.rake in the lib/tasks directory:

namespace :seed_data do
  desc 'Load seed data into the database of the current environment'
  task :load => :environment do
    require 'active_record/fixtures'
    Dir.glob(RAILS_ROOT + '/db/seed_data/*.yml').each do |file|
      Fixtures.create_fixtures('db/seed_data', File.basename(file, '.*'))
    end
  end
end

You can then issue the following command to load the seed data into the database. It will load into the development database by default — use the RAILS_ENV=production parameter to get it into the production database.

rake seed_data:load

Before you do that, however, you are going to need a Country model to access your countries through.

Generate a new model with code and name attributes:

script/generate model Country code:string name:string

Then migrate your database to create the new table:

rake db:migrate

I am using this reference data to populate country select lists, so I forked the country_select plugin and modified it to read the countries from the database. My version of the country_select plugin on can be installed by typing the following command:

script/plugin install git://github.com/johngrimes/country_select.git

Now you can use the following code in your views to output a country select list:

< % form_for @whatever do |form| %>
  < %= form.country_select :country %>
< % end %>

5 Responses to “Country list in YAML format, countries.yml”

  1. lewro says:

    I love the way you describe the whole process step by step in details. I am sure I will need this plugin one day.

  2. Laran Evans says:

    Great stuff. You’ve got a bug though in your countries.yml file. There’s no code for China. Thanks for putting time into this.

  3. johngrimes says:

    Thanks for the pickup. The list is now fixed and includes China.

  4. MrJack says:

    Thanks for that will be usefull !

  5. Eric says:

    I assume you’re putting this in the public domain? I’d love to use it.

Leave a Reply