Skip to content

Instantly share code, notes, and snippets.

@XORwell
Forked from Ch4s3/dump_db_to_json.rb
Created May 14, 2021 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XORwell/fe09e9be6530dc423cf2f02c11562def to your computer and use it in GitHub Desktop.
Save XORwell/fe09e9be6530dc423cf2f02c11562def to your computer and use it in GitHub Desktop.
Export local db to JSON and load that dump back to the db later
namespace :json do
desc 'Export all data to JSON files'
task :export => :environment do
Rails.application.eager_load!
ApplicationRecord.descendants.each do |model|
next if model.table_name.nil? || model.table_name == ''
begin
data = model.all
next if data == []
file = File.open(File.join(Rails.root, 'db', 'export', "#{model.table_name}.json"), 'w')
file.write data.to_json
file.close
rescue => e
puts e
end
end
end
desc 'Import all data from JSON files'
task :import => :environment do
Dir["./db/export/*.json"].each do |file|
table_name = file.split('/').last.split('.').first
class_type = table_name.classify.constantize
models = JSON.parse(File.read(file))
models.each do |model|
model_var = class_type.new(model)
model_var.save
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment