Created
December 10, 2014 19:47
-
-
Save brianburridge/8d2755a73dd5b4f0332b to your computer and use it in GitHub Desktop.
Export local db to JSON
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
namespace :json do | |
desc "Export all data to JSON files" | |
task :export => :environment do | |
Rails.application.eager_load! | |
ActiveRecord::Base.descendants.each do |model| | |
file = File.open(File.join(Rails.root, "db", "export", "#{model.table_name}.json"), 'w') | |
file.write model.all.to_json | |
file.close | |
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 | |
ActiveRecord::Base.connection.reset_pk_sequence!(table_name) | |
end | |
end | |
end | |
Note: Use at your own risk. Not meant for live production apps.
👍 Nice one.
For Rails 5 this should be updated to use ApplicationRecord.descendants
instead of ActiveRecord::Base.descendants
+1 @rchasman for Rails 5 note. Also I think it should be said that this doesn't work on a MySQL database. (Postgres only?)
Thanks for this! Also, you probably want to exclude the sessions table :)
A few gotchas I discovered:
- You may want to exclude the sessions table (and maybe others)
- If your model defines
as_json
you may not get all the data you expect - If your model defines default query behavior (like paranoia gem with
deleted_at
), you may not get all the data you expect
UPDATE: https://gist.github.com/synth/afe534267d79c7cfc696e0ec7a73c9d1
Made the script a bit more robust for larger data sets :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This rake task should be placed in the Rails app lib/tasks directory. It can then be run as:
It will produce JSON which you can check into git. Then push to Heroku. Then on Heroku run:
To import the data from JSON into the db.