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

后端 未结 11 1266
野的像风
野的像风 2020-12-07 14:54

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

11条回答
  •  攒了一身酷
    2020-12-07 15:29

    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.

提交回复
热议问题