Skip to content

Instantly share code, notes, and snippets.

@muZk
Created May 26, 2017 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muZk/07f40d326183e4290bbaeebcce29a799 to your computer and use it in GitHub Desktop.
Save muZk/07f40d326183e4290bbaeebcce29a799 to your computer and use it in GitHub Desktop.
Paperclip: how to move existing attachments to a new path

Paperclip: how to move existing attachments to a new path

Based on http://fernandomarcelo.com/2012/05/paperclip-how-to-move-existing-attachments-to-a-new-path/

For simplicity, I wanted to update my current attachments to a new directory.

My old model, VideoAttachment, had the following options:

class VideoAttachment < ActiveRecord::Base
  has_attached_file :video,
                    path: ':rails_root/uploads/:class/:id/:style/:filename',
                    url: '/images/:class/:style/:token',
                    styles: {
                        thumb: {
                            format: 'jpg'
                        }
                    }
end

My new version looks like this:

class VideoAttachment < ActiveRecord::Base

  has_attached_file :video,
                    styles: {
                        thumb: {
                            format: 'jpg'
                        },
                        webm: {
                            format: 'webm'
                        }
                    },
                    url: '/system/:class/:attachment/:id_partition/:style/:token.:extension',
end

Moving your current files

VideoAttachment.all.each do |video_attachment|

  old_options = {
    path: ':rails_root/uploads/:class/:id/:style/:filename',
    styles: {
        thumb: {
            format: 'jpg'
        }
    }
  }

  old_path = Paperclip::Attachment.new(:video, video_attachment, old_options).path
  file = File.new(old_path)
  video_attachment.video = file
  video_attachment.save
  file.close

end

Since I added a new style, I wanted to do a reprocess (which is done automatically by paperclip when you update the attachment).

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