Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# First configure your models to use Amazon s3 as storage option and setup the associated S3 config.
# Then add the classes your want to migrate in the klasses array below.
# Then run rake paperclip_migration:migrate_to_s3
# Should work but this is untested and may need some tweaking - but it did the job for me.
namespace :paperclip do
desc "migrate files from local filesystem to s3"
task :migrate_to_s3 => :environment do
Rails.application.eager_load!
ActiveRecord::Base.descendants.select do |d|
# fix PgSearch and any other gem that creates a model without a valid table
ActiveRecord::Base.connection.tables.include? d.table_name
end.each do |klass|
definitions = klass.try(:attachment_definitions) || {}
puts(definitions.blank? ? "Skipping #{klass.name} (no attachments)" : "Processing #{klass.name}")
klass.find_each do |record|
definitions.keys.each do |definition|
if !record.send("#{definition}_file_name")
puts "#{klass.name} #{record.id} has no attachment"
next
end
attachment = Paperclip::Attachment.new(definition.to_sym, record, definitions[definition.to_sym].except(:s3_credentials, :storage))
attachment_url = attachment.url(attachment.default_style, false)
attachment_path = (attachment.path[0] == '/' ? '' : Rails.root.to_s + "/public/system") + attachment.path
if !File.exists?(attachment_path)
puts "#{klass.name} #{record.id} has a dangling file path or is stored remotely"
next
end
File.open attachment_path do |file|
puts "#{attachment_path} => S3... "
record.update_attribute "#{definition}", file
end
end
end
puts ''
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.