[英]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: 但是它在视图中显示的错误是这个混乱:
I'd like it to be something a bit simpler, like "Avatar must be an image less than 2 megabytes" 我希望它有点简单,比如“阿凡达必须是一个小于2兆字节的图像”
However, I can't see where to do this, as passing :message => 'something'
throws an error Unknown validator: 'MessageValidator'
但是,我无法看到在哪里这样做,因为传递
:message => 'something'
会抛出错误Unknown validator: 'MessageValidator'
How do I go about cleaning this up? 我该如何清理呢?
Note that the happy path of uploading a small image works just fine. 请注意,上传小图片的快乐路径可以正常工作。
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. 一些进一步的测试表明,上传太大的图像(如桌面背景)或非.rb文件的内容会更优雅地失败,但根本不会显示任何错误消息。 Still not quite what I want.
仍然不是我想要的。
Obviously you solved this for yourself a long time ago, but for anyone who is looking for the answer, there is actually a way to do it within the provided validation. 显然你很久以前就已经为自己解决了这个问题,但是对于那些正在寻找答案的人来说,实际上有一种方法可以在提供的验证中做到这一点。
Simple add your message like so: 简单地添加你的消息,如下:
validates_attachment :avatar,
:content_type => { :content_type => /image/, :message => "Avatar must be an image" },
:size => { :in => 0..2.megabytes, :message => "Avatar must be less than 2 megabytes in size" }
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.