使用Carrierwave自定义进程我无法访问model.id(多页PDF)

时间:2013-03-15 15:32:12

标签: ruby ruby-on-rails-3 carrierwave rmagick

我的想法是,我想将PDF转换为每页图像。我已经尝试过Stackoverflow上的其他方法,但无济于事。以下是我的上传者文件。

上传

class PdfUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  #//TODO - Remove converted images when deleting an entry, maybe? if needed?

  storage :file

  #//TODO - Add images into the same folder. model.id can't be accessed in a custom process.

  def store_dir
    "#{Rails.root}/public/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
  def cache_dir
    "#{Rails.root}/public/uploads/#{model.class.to_s.underscore}/#{mounted_as}/tmp"
  end

  def extension_white_list
    %w(pdf)
  end

  def filename
    super.chomp(File.extname(super)) + '.png'
  end

  version :pages do
    process :create_pages
    process convert: 'png'
  end

  process convert: 'png'

  version :thumb do
    process :cover
    process :resize_to_fill => [200, 200, Magick::CenterGravity]
    process convert: 'png'
  end

  def cover
    manipulate! do |frame, index|
      frame if index.zero?
    end
  end

  def create_pages
    manipulate! do |frame, index|
      frame.write("#{store_dir}/#{index}.png")
    end
  end

end

PDF将转换为每页的图像。但它无法识别model.id并将其存储在该文件夹中。相反,它将存储在上面的目录中。 我已经尝试添加以下内容来强制制作文件夹,但它似乎不知道model.id通过一些测试?

试图制作导演

def create_pages
    Dir.mkdir(store_dir) unless File.exists?(store_dir)
    manipulate! do |frame, index|
      frame.write("#{store_dir}/#{index}.png")
    end
  end 

非常感谢帮助,我已经坚持了一段时间,并且因为沮丧而不得不离开它几天。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

这很可能是因为您在保存模型本身之前使用frame.write保存图像,因此也在分配ID之前保存图像。

请查看有关潜在解决方案的答案:Carrierwave : error with model.id in the store_path