Created
June 1, 2021 09:24
-
-
Save satnami/e87bcc5524650aaf5450cdfa1bfec06f to your computer and use it in GitHub Desktop.
Dump DB to YML Fixtures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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