Skip to content

Instantly share code, notes, and snippets.

@brianburridge
Created December 10, 2014 19:47
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save brianburridge/8d2755a73dd5b4f0332b to your computer and use it in GitHub Desktop.
Save brianburridge/8d2755a73dd5b4f0332b to your computer and use it in GitHub Desktop.
Export local db to JSON
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
@brianburridge
Copy link
Author

This rake task should be placed in the Rails app lib/tasks directory. It can then be run as:

rake json:export

It will produce JSON which you can check into git. Then push to Heroku. Then on Heroku run:

rake json:import

To import the data from JSON into the db.

@brianburridge
Copy link
Author

Note: Use at your own risk. Not meant for live production apps.

@lacostenycoder
Copy link

👍 Nice one.

@rchasman
Copy link

For Rails 5 this should be updated to use ApplicationRecord.descendants instead of ActiveRecord::Base.descendants

@aaronkelton
Copy link

+1 @rchasman for Rails 5 note. Also I think it should be said that this doesn't work on a MySQL database. (Postgres only?)

@synth
Copy link

synth commented Feb 20, 2021

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