Last active
July 6, 2018 14:08
-
-
Save artemv/5aed83a450cade41685763f19cba3bf4 to your computer and use it in GitHub Desktop.
Migrate file uploads from database to Amazon S3 in Rails
This file contains 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
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