载波-处理期间无法访问model.id

时间:2019-07-06 16:29:12

标签: ruby-on-rails carrierwave

我正在上传PDF,并希望将页面分成单独的图像。我的问题是,处理是在保存原始pdf之前进行的,因此model.id为null。我需要model.id,以便可以跟踪图像文件并将它们存储在正确的文件夹中。

class PdfPackageUploader < CarrierWave::Uploader::Base

include CarrierWave::MiniMagick

storage :file

def store_dir
"uploads/#{model.class.to_s.underscore}/#{model.id}"
end

version :jpg do
  process :convert_to_images
  process :set_content_type_jpg
end

def convert_to_images(*args)
  image = MiniMagick::Image.open(current_path)
  image.pages.each_with_index do |page, index|
    MiniMagick::Tool::Convert.new do |convert|
      convert.background 'white'
      convert.flatten
      convert.density 200
      convert.quality 80
      convert << page.path
      convert << "#{CarrierWave.root}/#{store_dir}/#{model.id}image-#{index}.jpg"
      @sheet = Sheet.create()
      @sheet.package_id = model.id
      @sheet.save
    end
  end
end

def set_content_type_jpg(*args)
  self.file.instance_variable_set(:@content_type, "image/jpg")
end

def extension_white_list
  %w(jpg jpeg gif png doc docx pdf)
end

0 个答案:

没有答案