Rails 3 + Paperclip: move current data to another folder

Since I'm new to Rails, I made a mistake in using the default path (/ system /: attachment /: id /: style /: filename) in 4 different models. Now I would like to move each model to its own folder, but without losing the old data.

What is the right way to handle this? Does Paperclip automatically transfer data from old folders?

Thank.

+3
source share
2 answers

In the end, I created a small rake task. Assuming you have a model called “User” and your image file is called “image”, put the following code in lib / tasks / change_users_folder.rb

desc "Change users folder"
task :change_users_folder => :environment do
  @users = User.find :all
  @users.each do |user|
    unless user.image_file_name.blank?
      filename = Rails.root.join('public', 'system', 'images', user.id.to_s, 'original', user.image_file_name)

      if File.exists? filename
        user.image = File.new filename
        user.save
      end
    end
  end
end

, rake change_users_folder .

, . , . , .

: : url paperclip:)

+2

. , , .

, . , ?

. ( - Attachment, Paperclip:: Attachment: )

task :move_attachments_to_institution_folders => :environment do
attachments = Attachment.all
puts "== FOUND #{attachments.size} ATTACHMENTS =="
old_path_interpolation = APP_CONFIG[ 'paperclip_attachment_root' ] + "/:id_partition.:extension"
new_path_interpolation = APP_CONFIG[ 'paperclip_attachment_root' ] + "/:institution/reports/:id_:filename"
attachments.each do |attachment|
    # the interpolate method of paperclip takes the symbol variables and evaluates them to proper path segments.
    old_file_path = Paperclip::Interpolations.interpolate(old_path_interpolation, attachment.file, attachment.file.default_style) #see paperclip docs
    puts "== Current file path:  #{old_file_path}"
    new_file_path = Paperclip::Interpolations.interpolate(new_path_interpolation, attachment.file, attachment.file.default_style)
    if File.exists?(old_file_path)
        if !File.exists?(new_file_path) #don't overwrite
            FileUtils.mkdir_p(File.dirname(new_file_path)) #create folder if it doesn't exist
            FileUtils.cp(old_file_path, new_file_path)
            puts "==== File copied (^_^)"
        else
            puts "==== File already exists in new location."
        end
    else
        puts "==== ! Real File Not Found ! "
    end
end

, paperclip , . FileUtils . .

P.S. 2.3.8, paperclip -v 2.8.0

+3

All Articles