Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save artemv/5aed83a450cade41685763f19cba3bf4 to your computer and use it in GitHub Desktop.
Save artemv/5aed83a450cade41685763f19cba3bf4 to your computer and use it in GitHub Desktop.
Migrate file uploads from database to Amazon S3 in Rails
task migrate_file_uploads_from_database_to_amazon: :environment do
Document.find_each do |d| # Document is our ActiveRecord model containing the `data` binary column (bytea Postgres type)
next if ENV['ID'] && d.id.to_s != ENV['ID'] # be able to say `ID=225 rake migrate_file_uploads_from_database_to_amazon` to process single record
next unless d.data # d.data is a binary column we were storing files at
print d.id
dir = "tmp/#{d.id}"
Dir.mkdir(dir) unless Dir.exist?(dir)
name = d.read_attribute(:name)
path = "#{dir}/#{name}"
File.open(path, "w+b") do |f|
f.write d.data
end
File.open(path) do |f|
d.document_file = f # new column mounted with Carrierwave generated DocumentUploader
d.save!
end
print '.'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment