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

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

    I used this in Rails 6:

    # How to run:
    # rake fixtures:import_db_table[my_table]
    namespace :fixtures do
      desc 'Convert development table into Rails test fixtures'
      task :import_db_table, [:table_name] => :environment do |_task, args|
        begin
          table_name = args[:table_name]
          raise "Missing table name" if table_name.blank?
          conter = '000'
          file_path = "#{Rails.root}/spec/fixtures/#{table_name}.yml"
          ActiveRecord::Base.establish_connection
          File.open(file_path, 'w') do |file|
            rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name}")
            data = rows.each_with_object({}) do |record, hash|
              suffix = record['id'].blank? ? conter.succ! : record['id']
              hash["#{table_name.singularize}_#{suffix}"] = record
            end
            puts "Writing table '#{table_name}' to '#{file_path}'"
            file.write(data.to_yaml)
          end
        ensure
          ActiveRecord::Base.connection.close if ActiveRecord::Base.connection
        end
      end
    end
    

    Extracted from here (which imports all tables).

提交回复
热议问题