Forked from brianburridge/gist:8d2755a73dd5b4f0332b
Last active
May 14, 2021 15:17
-
-
Save Ch4s3/d6af9c942505f4647f777be4a00a73ad to your computer and use it in GitHub Desktop.
Export local db to JSON and load that dump back to the db later
This file contains 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
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