Skip to content

Instantly share code, notes, and snippets.

@satnami
Created June 1, 2021 09:24
Show Gist options
  • Save satnami/e87bcc5524650aaf5450cdfa1bfec06f to your computer and use it in GitHub Desktop.
Save satnami/e87bcc5524650aaf5450cdfa1bfec06f to your computer and use it in GitHub Desktop.
Dump DB to YML Fixtures
# https://stackoverflow.com/a/12188782
namespace :db do
namespace :fixtures do
desc 'Create YAML test fixtures from data in an existing database. Defaults to development database. Specify RAILS_ENV=production on command line to override.'
task :dump => :environment do
sql = 'SELECT * FROM %s ORDER BY ID'
skip_tables = ['schema_migrations']
# ActiveRecord::Base.establish_connection(Rails.env)
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
i = '000'
data = ActiveRecord::Base.connection.select_all(sql % table_name)
data = data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}
# don't create when there is no data
if data != {}
File.open("#{Rails.root}/test/fixtures/#{table_name}.yml.new", 'w') do |file|
file.write data.to_yaml
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment