Rails 4 中的回形针尺寸验证错误

Paperclip dimension validation error in Rails 4

我希望我的应用程序用户能够使用

上传文件

at least width:800px and height: 550px

我在app/models/dimensions_validator.rb文件中创建 和代码

class DimensionsValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path)
    width = options[:width]
    height = options[:height] 

    record.errors[attribute] << "Width must be at least #{width}px" if dimensions.width < width
    record.errors[attribute] << "Height must be at least #{height}px" if dimensions.height < height
  end
end

在我的 app/models/gig.rb 模型中

validates :image, :dimensions => { :width => 800, :height => 550 }

Question: When i click on the submit button,without actually selecting any picture,it throughs an error saying undefined method "path" for nil:NilClass and it marks in red color the line 4 which is dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path)

也许我需要一个代码来检查图像是否存在,类似于 if image.present? 但我应该把它放在哪里?我已经在 gig 模型中使用 validates_attachment_presence :image

这是错误

这是我的 GigsController#update

def update
    if @gig.update(gig_params)
      redirect_to @gig, notice: "Gig was successfully updated"
    else
      render "edit"
    end
  end

我相信您可以在验证中添加其他条件。因此,您可以尝试添加 allow_blankif 条件:

validates :image, dimensions: { width: 800, height: 550 }, allow_blank: true

或者也许:

validates :image, dimensions: { width: 800, height: 550 }, if: Proc.new {|gig| gig.image? }

试试这个。

validates :image, :unless => "image.queued_for_write[:original].blank?", dimensions: { width: 800, height: 550 }

可以使用此 gem 通过 Paperclip 验证图像宽度和高度:https://github.com/evedovelli/image_validators

将其添加到您的捆绑包中:

gem 'image_validators'

并将验证规则添加到您的模型中:

validates :image, dimensions: { greater_than_or_equal_to: { width: 800, height: 550 } }