Changing attachment :path

121onto edited this page Mar 7, 2016 · 6 revisions

After changing attachment's :path setting images need to be recreated. You can use the following rake task

# Assuming you had a model like this
#
# class Post
#   has_attached_file :image, :path => ":rails_root/public/system/:attachment/:id/:style/:filename"
# end

namespace :paperclip do
  desc "Recreate attachments and save them to new destination"
  task :move_attachments => :environment do

    Post.find_each do |post|
      unless post.image_file_name.blank?
        filename = Rails.root.join('public', 'system', 'images', post.id.to_s, 'original', post.image_file_name)

        if File.exists? filename
          puts "Re-saving image attachment #{post.id} - #{filename}"
          image = File.new filename
          post.image = image
          post.save
          # if there are multiple styles, you want to recreate them :
          post.image.reprocess! 
          image.close
        end
      end
    end
  end
end

Here is a gist for changing the path using a migration. The example uses google cloud storage instead of local storage:

https://gist.github.com/121onto/acc588b859893ddacebf

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.