Ruby on rails Rails Carrierwave和Imagemagick,使用条件调整图像大小

Ruby on rails Rails Carrierwave和Imagemagick,使用条件调整图像大小,ruby-on-rails,imagemagick,carrierwave,Ruby On Rails,Imagemagick,Carrierwave,我一直在努力寻找任何教程或问题,解释如何上传图像,并根据用户提供的特定条件调整大小 我可以很容易地上传和调整图像大小使用硬编码的值,但我坚持使用用户提供的参数从上传访问 我希望根据用户检查图像的大小,将图像大小调整为800x600或300x300 为此,我在模型结构中有一个名为large的布尔列 在上传程序中,我可以在store_dir块中轻松访问模型及其值,但在该块之外的任何地方,任何模型属性都返回为nil 这就是我想做的:- class BannerUploader < Carrier

我一直在努力寻找任何教程或问题,解释如何上传图像,并根据用户提供的特定条件调整大小

我可以很容易地上传和调整图像大小使用硬编码的值,但我坚持使用用户提供的参数从上传访问

我希望根据用户检查图像的大小,将图像大小调整为800x600或300x300

为此,我在模型结构中有一个名为large的布尔列

在上传程序中,我可以在store_dir块中轻松访问模型及其值,但在该块之外的任何地方,任何模型属性都返回为nil

这就是我想做的:-

class BannerUploader < CarrierWave::Uploader::Base
    include CarrierWave::MiniMagick
    storage :file
    def store_dir
        "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
    end
    resize_to_fit(800,600) if model.large==true
    resize_to_fit(300,300) if model.large!=true
end
但是,这将返回错误 BannerUploader:类的未定义局部变量或方法“model”


如何处理此问题。

要处理原始文件,可以指定自定义方法:

class BannerUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  process :process_original_version

  def process_original_version
    if model.large
      resize_to_fit(800,600)
    else
      resize_to_fit(300,300)
    end
  end
end
对于特定版本:

class BannerUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :normal do
    if model.large
      process resize_to_fit: [800,600]
    else
      process resize_to_fit: [300,300]
    end
  end
end

好的,那么@Alex Kojin的答案是正确的。然而,我也面临着另一个问题。当用户提交表单时,图像大小将始终调整为300x300,因为出于某种原因,将首先执行图像大小调整过程,然后将“大”属性设置为true。因此,上传程序总是将model.large设置为false。 这就是我改变动作控制器的方法

def create
    @banner=Banner.new
    @banner.large=params[:large]
    @banner.update_attributes(banner_params)
    @banner.save
    redirect_to :back
end
不确定这是否是正确的方法,但对我来说确实有效。

我认为这对您有帮助