在 Rails 2 应用程序中验证附件内容类型 Paperclip
Validate attachment content type Paperclip in Rails 2 application
在我的 Rails 2 应用程序中,产品图片是使用 Paperclip 作为插件上传的。我需要将图像类型限制为 jpeg 和 png,并且即使未上传图像也允许保存产品。
当前代码是
has_attached_file :master_image,
:url => "/images/products/:id/private/master.img",
:path => ":rails_root/public/images/products/:id/private/master.img"
validates_attachment_content_type :master_image, :content_type => ['image/png', 'image/jpg'] , :message => "image must be jpg or png." , :allow_nil => true
我添加了 :allow_nil => true
但它不起作用。
我在尝试不带图像的情况下保存时出现 image must be jpg or png
。
是否只有包含附件才能进行验证?
尝试不带图像保存时,您得到 image must be jpg or png
,因为如果图像不存在,这意味着内容类型也丢失,即它们不是 jpg
或 png
.
为了完成您的任务,您可以添加一个自定义验证器,首先您将检查图像是否存在,如果是,然后您将检查图像的 :content_type
。
将这些添加到您的 Product
模型中:
validate :master_image_type_present
def master_image_type_present
if master_image.present? && !(['image/png', 'image/jpg', 'image/jpeg'].include? master_image_content_type)
errors.add(:content_type, "invalid content type")
end
end
而且,您的验证将按预期工作。
在我的 Rails 2 应用程序中,产品图片是使用 Paperclip 作为插件上传的。我需要将图像类型限制为 jpeg 和 png,并且即使未上传图像也允许保存产品。
当前代码是
has_attached_file :master_image,
:url => "/images/products/:id/private/master.img",
:path => ":rails_root/public/images/products/:id/private/master.img"
validates_attachment_content_type :master_image, :content_type => ['image/png', 'image/jpg'] , :message => "image must be jpg or png." , :allow_nil => true
我添加了 :allow_nil => true
但它不起作用。
我在尝试不带图像的情况下保存时出现 image must be jpg or png
。
是否只有包含附件才能进行验证?
尝试不带图像保存时,您得到 image must be jpg or png
,因为如果图像不存在,这意味着内容类型也丢失,即它们不是 jpg
或 png
.
为了完成您的任务,您可以添加一个自定义验证器,首先您将检查图像是否存在,如果是,然后您将检查图像的 :content_type
。
将这些添加到您的 Product
模型中:
validate :master_image_type_present
def master_image_type_present
if master_image.present? && !(['image/png', 'image/jpg', 'image/jpeg'].include? master_image_content_type)
errors.add(:content_type, "invalid content type")
end
end
而且,您的验证将按预期工作。