Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save synth/afe534267d79c7cfc696e0ec7a73c9d1 to your computer and use it in GitHub Desktop.
Save synth/afe534267d79c7cfc696e0ec7a73c9d1 to your computer and use it in GitHub Desktop.
Export local db to JSON
Rails.application.eager_load!
exclude_tables = ["sessions"]
row_limit_per_table = nil
tables = []
ApplicationRecord.descendants.each do |model|
next if exclude_tables.any?{ |skip_table| skip_table == model.table_name }
next if tables.include?(model.table_name) # This covers STI
puts "Exporting: #{model.table_name}"
filename = File.join(Rails.root, "db", "export", "#{model.table_name}.json")
file = File.open(filename, 'w')
file.write "["
find_each_opts = {}
find_each_opts[:finish] = row_limit_per_table if row_limit_per_table.present?
model.find_each(find_each_opts) do |obj|
file.write obj.attributes.to_json
file.write ","
end
tables << model.table_name
file.write "]"
file.close
`sed -i.bak 's/\,\]/\]/' #{filename}`
end
`rm db/export/*.bak`
@synth
Copy link
Author

synth commented Mar 11, 2021

What version of rails?

@jmarsh24
Copy link

6.1

@synth
Copy link
Author

synth commented Mar 12, 2021

That's probably it. I wrote the above on 5.x. We're in the process of migrating our app to 6.x, but can't help until that's complete. Let me know if you find the cause!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment