Cleaning up Paperclip error messages

坚强是说给别人听的谎言 提交于 2019-12-18 13:38:27

问题


Okay, so i've got paperclip working, and I'm trying to use the built in validator to make sure that the file uploaded

  1. Is an image
  2. Is not too big

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"

However, I can't see where to do this, as passing :message => 'something' throws an error 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. Still not quite what I want.


回答1:


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" }



回答2:


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


来源:https://stackoverflow.com/questions/10711504/cleaning-up-paperclip-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!