如何使用rake任务将图像上传到Rackspace云文件?

时间:2013-12-16 09:12:57

标签: ruby-on-rails rake carrierwave rackspace-cloud fog

我尝试使用Fog / Carrierwave /与Rackspace云文件。我在生产服务器上有大量上传的图像。我尝试使用下面的rake任务将这些图像上传到Rackspace Cloud Files。

desc 'Transfer photos to rackspace'
task :photos => :environment do
  photos = Photo.order(created_at: :desc).limit(10)
  photos.each do |photo|
    if photo.attachment?
      photo.attachment.recreate_versions!
      photo.save!
    else
      puts "================================= ATTACHMENT NOT FOUND: ID: #{photo.id}"
    end
  end
end

但我得到以下错误:

rake aborted!
undefined method `body' for nil:NilClass
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/gems/carrierwave-0.9.0/lib/carrierwave/storage/fog.rb:227:in `read'
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/gems/carrierwave-0.9.0/lib/carrierwave/uploader/cache.rb:77:in `sanitized_file'
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/gems/carrierwave-0.9.0/lib/carrierwave/uploader/cache.rb:116:in `cache!'
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/gems/carrierwave-0.9.0/lib/carrierwave/uploader/versions.rb:225:in `recreate_versions!'
/home/zeck/code/bee/lib/tasks/bee.rake:9:in `block (4 levels) in <top (required)>'
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/gems/activerecord-4.0.1/lib/active_record/relation/delegation.rb:13:in `each'
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/gems/activerecord-4.0.1/lib/active_record/relation/delegation.rb:13:in `each'
/home/zeck/code/bee/lib/tasks/bee.rake:7:in `block (3 levels) in <top (required)>'
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/bin/ruby_noexec_wrapper:14:in `eval'
/home/zeck/.rvm/gems/ruby-2.0.0-p247@rails-4-1/bin/ruby_noexec_wrapper:14:in `<main>'

表示未存储在Rackspace Cloud Files中的图像。你们有类似的佣金任务吗?请分享给我。或者指导我。

感谢您的建议:D

1 个答案:

答案 0 :(得分:4)

当您将CarrierWave上传者的storage:file更改为:fog时,它会丢失对原始上传的图片文件路径的跟踪,因此recreate_versions!等方法并且store!将无法找到要上传的文件。

如果您手动告诉CarrierWave旧路径,它会将它们上传到Cloud Files:

desc 'Transfer photos to rackspace'
task :photos => :environment do
  photos = Photo.order(created_at: :desc).limit(10)
  photos.each do |photo|
    if photo.attachment?
      # If you've overridden the storage path in the uploader, you'll need to
      # use a different path here.
      #
      # "photo[:attachment]" is used to get the actual attribute value instead
      # of the mounted uploader -- the base filename of the attachment file.
      path = Rails.root.join('public', 'uploads', photo[:attachment])

      unless path.exist?
        puts "#{path} doesn't exist. Double check your paths!"
        next
      end

      photo.attachment = path.open
      photo.save!
      puts "transferred #{photo.id}"
    else
      puts "================================= ATTACHMENT NOT FOUND: ID: #{photo.id}"
    end
  end
end