回形针在销毁时触发验证错误

Paperclip triggers validation error on destroy

我的回形针模型中有这个功能:

def ratiocorrect
    ratio = Paperclip::Geometry.from_file(image.queued_for_write[:original].path).width / Paperclip::Geometry.from_file(image.queued_for_write[:original].path).height
    if ratio < 1.499 or ratio > 1.501
      errors.add(:image,'ratio should be 4:3')
    end
  end

它会在保存图像之前检查其比例是否为 3:2。

我强制执行此操作:

validate :ratiocorrect

而且它运行完美。

虽然当我想销毁图像时出现以下错误:

undefined method `path' for nil:NilClass
ratio = Paperclip::Geometry.from_file(image.queued_for_write[:original].path).width / Paperclip::Geometry.from_file(image.queued_for_write[:original].path).height

它似乎正在再次检查 queued_for_write 图像,因为有 none 用于销毁操作。

是否可以仅在创建或更新时验证,而不是销毁时验证?

是的,使用 :create and/or :update 选项进行自定义验证。

你会做这样的事情:

validate :ratiocorrect, on: :create

By default, such validations will run every time you call valid? or save the object. But it is also possible to control when to run these custom validations by giving an :on option to the validate method, with either: :create or :update.

查看 Custom Methods 了解更多信息。