上传现有的图片版本,使其成为自己的" base"图片

时间:2017-03-08 21:24:26

标签: ruby-on-rails ruby carrierwave

如何通过Carrierwave重新上载现有的图像版本,例如thumb_xyz.jpg,这样缩略图就会成为它自己的基础"图像?

我试过搞乱商店!上传者,但我无法让它工作......

uploader.ImageUploader.new
uploader.store!(image_url(:thumb))

1 个答案:

答案 0 :(得分:0)

这是一个可以调整和修改以满足您需求的解决方案!它会导致原始父图像具有自己的裁剪版本,以及裁剪内容的完全独立的基本图像。通常在Carrierwave中使用和引用的父图像裁剪版本用作排序的占位符,作为生成新基本图像的手段。所以在实践中,它会随着每一种作物不断变化。

如果将上传器安装到模型类上(如此处所示),则需要通过关联的控制器完成工作,而不是在上传器或模型类中完成。这非常重要。

在这种情况下,由于目标是选择性地拉出并上传现有的图像版本,并且由于裁剪本身作为控制器更新操作的一部分发生,因此在那里添加了代码。要理解的重要事项之一是文件裁剪文件本身的位置:@image.image.versions[:crop]。有了这些知识,那么只需要将其作为参数传递。

images_controller.rb
...
def update
  respond_to do |format|
    if @image.update(image_params)
      format.html { redirect_to @image, notice: 'Image was successfully updated.'}
      format.json { render :show, status: :ok, location: @image }

      #### HERE IS THE SOLUTION ###
      @crop_image = current_user.images.build(image: @image.image.versions[:crop])
      if @crop_image.save
        format.html { redirect_to @crop_image, notice: 'Crop image successfully created.'}
        format.json { render :show, status: :created, location: @crop_image }
      else
        format.html { render :new, notice: 'Crop image could not be saved for some reason...'}
    end
  else
    format.html { render :edit }
    format.json { render json: @image.errors, status: :unprocessable_entity }
  end
end