Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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`
@jmarsh24
Copy link

Could you provide some instructions on how to run this script?

@jmarsh24
Copy link

Exporting: admin_users
Traceback (most recent call last):
3: from (irb):5:in <main>' 2: from (irb):5:in each'
1: from (irb):17:in `block in

'
ArgumentError (wrong number of arguments (given 1, expected 0))

I receive this error when I try to run it direction in console.

@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