清理回形针错误消息 [英] Cleaning up Paperclip error messages
问题描述
好的,所以我已经使用回形针了,我正在尝试使用内置的验证器来确保文件已上传
Okay, so i've got paperclip working, and I'm trying to use the built in validator to make sure that the file uploaded
- 是图像
- 不是太大
所以我在模型,根据文档:
So I have this in the model, per the documentation:
validates_attachment :avatar,
:content_type => { :content_type => /image/ },
:size => { :in => 0..2.megabytes }
然而,视图中显示的错误是这样的混乱:
However the error it shows in the view is this mess:
我希望它更简单一些,例如头像必须是小于2 MB的图像
I'd like it to be something a bit simpler, like "Avatar must be an image less than 2 megabytes"
但是,我可以看不到在哪里做,因为传递:message => '某物'
引发错误未知验证器:'MessageValidator'
However, I can't see where to do this, as passing :message => 'something'
throws an error Unknown validator: 'MessageValidator'
我该如何要清理吗?
请注意,上传小图像的快乐路径就很好。
Note that the happy path of uploading a small image works just fine.
进一步的测试表明,上传太大的图像(如桌面背景)或非.rb文件的图像会更正常地失败,但根本不显示任何错误消息。
Some further testing shows that uploading an image that's too big (like a desktop background) or something that's not a .rb file fails more gracefully, but doesn't display any error message at all. Still not quite what I want.
推荐答案
我最终写了两个自定义验证器。确实,这些功能与回形针验证器的功能相同,但它们的外观更美:
I ended up writing two custom validators. It's true that these do the same thing the paperclip validators do, but they fail prettier:
def avatar_is_a_image
if self.avatar?
if !self.avatar.content_type.match(/image/)
errors.add(:avatar, "Avatar must be an image")
end
end
end
def avatar_is_less_than_two_megabytes
if self.avatar?
if self.avatar.size > 5.megabytes
errors.add(:avatar, "Avatar must be less than 5 megabytes in size")
end
end
end
这篇关于清理回形针错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!