Best way to export a database table to a YAML file?

29,261

Solution 1

There is a rake task for this. You can specify RAILS_ENV if needed; the default is the development environment:

rake db:fixtures:dump
    # Create YAML test fixtures from data in an existing database.

Solution 2

I have been using YamlDb to save the state of my database.

Install it with the following command:

script/plugin install git://github.com/adamwiggins/yaml_db.git 

Use the rake task to dump the contents of Rails database to db/data.yml

rake db:data:dump

Use the rake task to load the contents of db/data.yml into the database

rake db:data:load

This is the creators homepage:

http://blog.heroku.com/archives/2007/11/23/yamldb_for_databaseindependent_data_dumps/

Solution 3

This plugin will add the functionality you want. It was extracted from ActiveRecord so no longer comes by default.

script/plugin install http://github.com/topfunky/ar_fixtures

Then run:

rake db:fixtures:dump MODEL=ModelName

Solution 4

For Rails 3, if you want to dump yaml from the DB and use it as a fixture, I use this code:

module DbToFixture

  TEMP_FIXTURE_PATH = Rails.root.join("test", "new_fixtures")

  def fixturize(model)
    Dir.mkdir(TEMP_FIXTURE_PATH) unless File.exists?(TEMP_FIXTURE_PATH)
    fname = model.table_name
    file_path = TEMP_FIXTURE_PATH.join(fname)
    File.open(file_path, 'w') do |f|
      model.all.each do |m|
        f.write(m.to_yaml)
      end
    end
  end

end

I just run it from the console with

require './lib/db_to_fixture'
include DbToFixture
fixturize ModelName

I have not been able to get ar_fixtures to work with Rails 3 (haven't tried very hard though). Yaml db is great for dumping and saving the db, but its format is not compatible with fixtures.

Solution 5

Iron Fixture Extractor was built for exactly this purpose. It's particularly good for situations where you want to use different fixture sets for different testing scenarios (rather than having all fixtures for all tests). It provides functionality for extracting, loading, rebuilding fixtures, truncating tables, or snagging particular hashes from your fixture yaml files.

Share:
29,261
Mattew
Author by

Mattew

Updated on June 25, 2020

Comments

  • Mattew
    Mattew about 4 years

    I have some data in my development database that I would like to utilize as fixtures in my test environment. What is the best way in Rails 2.x to export a database table to a YAML fixture?