How to seed your database with JSON/YAML data in Rails 2.3.4
In Rails 2.3.4 there’s a new rake task called db:seed that allows you to seed your database with data. To use it you first need a file called db/seed.rb. In it put the code that creates the ActiveRecord objects your application needs.
You can load and execute SQL from an external file, or plain Ruby objects from YAML or JSON as I’ll show you in this example.
Put this in db/seed.rb:
1 json = ActiveSupport::JSON.decode(File.read('db/seeds/countries.json')) 2 3 json.each do |a| 4 Country.create!(a['country']) 5 end
Next export the data from an existing database by running the following command in the Rails console:
1 File.open('db/seeds/countries.json', 'w') { |f| f << Country.all.to_json }
Now when you run rake db:seed, Rails will load the countries.json file and insert the data into your database.
Pretty print JSON data
You’ll probably want to pretty print your data if you’re going to manually edit it. This can be done by following the instructions in this snippet
Bootstraping your database with rake
In lib/tasks/app.rake:
1 namespace :db do 2 desc "Bootstraps the database" 3 task :bootstrap => ['db:schema:load'] do 4 5 { 'Ruby' => 'ruby', 6 'JavaScript' => 'javascript', 7 }.each do |name, short_name| 8 Category.create!(:name => name, :short_name => short_name) 9 end 10 11 end 12 end