DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Victor has posted 16 posts at DZone. View Full User Profile

Data Export Using Migrations

02.02.2006
| 645 views |
  • submit to reddit
        // ...dumping the data to fixture files, comes in handy:

task :dump_fixtures => :environment do
   path = ENV['DEST'] || "#{RAILS_ROOT}/test/fixtures"
   db   = ENV['DB']   || 'development'
   sql  = 'SELECT * FROM %s'

   ActiveRecord::Base.establish_connection(db)
   ActiveRecord::Base.connection.select_values('show tables').each do |table_name|
      i = '000'
      File.open("#{path}/#{table_name}.yml", 'wb') do |file|
         file.write ActiveRecord::Base.connection.select_all(sql %
         table_name).inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
         }.to_yaml
         puts "Writing #{file.to_s}"
      end
   end
end