回形针通过延迟作业上传到S3

时间:2015-08-29 02:40:09

标签: ruby-on-rails paperclip delayed-job

我正在尝试使用带有delayed_job gem的Rails(4.2)将文件上传到s3。

我的代码基本上是这篇文章中显示的内容:http://airbladesoftware.com/notes/asynchronous-s3/(稍有修改)。

照片模式

class Photo < ActiveRecord::Base
  belongs_to :gallery

  has_attached_file :local_photo,
                    path: ":rails_root/public/system/:attachment/:id/:style/:basename.:extension",
                    url:  "/system/:attachment/:id/:style/:basename.:extension"

  has_attached_file :image,
                    styles: {large: '500x500#', medium: '180x180#'},
                    storage:         :s3,
                    s3_credentials:  lambda { |attachment| attachment.instance.s3_keys },
                    s3_permissions:  :private,
                    s3_host_name:    's3-sa-east-1.amazonaws.com',
                    s3_headers:      {'Expires'             => 1.year.from_now.httpdate,
                                      'Content-Disposition' => 'attachment'},
                    path:            "images/:id/:style/:filename"


  validates_attachment_content_type :image,
                                    content_type: [
                                      "image/jpg", 
                                      "image/jpeg", 
                                      "image/png"]

  def s3_keys
    {
      access_key_id: SECRET["key_id"],
      secret_access_key: SECRET["access_key"],
      bucket: SECRET["bucket"]
    }
  end

  after_save :queue_upload_to_s3

  def queue_upload_to_s3
     Delayed::Job.enqueue ImageJob.new(id) if local_photo? && local_photo_updated_at_changed?
  end

  def upload_to_s3
    self.image = Paperclip.io_adapters.for(local_photo)
    save!
  end
end


class ImageJob < Struct.new(:image_id)
  def perform
    image = Photo.find(image_id)
    image.upload_to_s3
    image.local_photo.destroy
  end
end

使用此代码,作业(ImageJob)在后台运行(我可以在delayed_job_web上看到它),没有错误。但是文件没有上传。

如果我“禁用后台”并仅使用:

ImageJob.new(id).perform if local_photo? && local_photo_updated_at_changed?

文件上传到亚马逊,本地文件也被删除。

有什么建议吗?

提前致谢

更新#1 现在我可以看到错误:

Job failed to load: undefined class/module ImageJob. Handler: "--- !ruby/struct:ImageJob\nimage_id: 412\n"

更新#2 我使用delay方法进行此操作,如下所示:

  def perform
    if local_photo? && local_photo_updated_at_changed?
      self.delay.move_to_s3
    end
  end

0 个答案:

没有答案