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

后端 未结 11 1298
野的像风
野的像风 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:26

    Here's a rake task that will do exactly that (tested in Rails 3.2.8):

    namespace :db do
        task :extract_fixtures => :environment do
          sql  = 'SELECT * FROM "%s"'
          skip_tables = ["schema_migrations"]
          ActiveRecord::Base.establish_connection
          if (not ENV['TABLES'])
            tables = ActiveRecord::Base.connection.tables - skip_tables
          else
            tables = ENV['TABLES'].split(/, */)
          end
          if (not ENV['OUTPUT_DIR'])
            output_dir="#{Rails.root}/test/fixtures"
          else
            output_dir = ENV['OUTPUT_DIR'].sub(/\/$/, '')
          end
          (tables).each do |table_name|
            i = "000"
            File.open("#{output_dir}/#{table_name}.yml", 'w') do |file|
              data = ActiveRecord::Base.connection.select_all(sql % table_name.upcase)
              file.write data.inject({}) { |hash, record|
                hash["#{table_name}_#{i.succ!}"] = record
                hash
              }.to_yaml
              puts "wrote #{table_name} to #{output_dir}/"
            end
          end
        end
    end
    

    Source: http://sachachua.com/blog/2011/05/rails-exporting-data-specific-tables-fixtures/

    Note: I had to make a few changes to the blog code to make it more cross-database compatible and work in Rails 3.2

提交回复
热议问题