问题
I use paperclip to attach an avatar to users, which works fine but when a new user attempts to register it complains about the avatar bieng too small and not of the right type.
This is how i validate my avatars:
validates_attachment_size :avatar, :less_than => 1.megabytes
validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png', 'image/gif']
This is the error i get when i try to register.
There were problems with the following fields:
* Avatar file size file size must be between 0 and 1048576 bytes.
* Avatar content type is not included in the list
is there anyway to make it so that avatar can be blank?
回答1:
I don't know if this is gonna work but try:
validates_attachment_size :avatar, :less_than => 1.megabytes, :if => avatar_changed?
validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png', 'image/gif'], :if => avatar_changed?
回答2:
I didn't use paperclip, but in general in Rails you can add condition to decide if validations should be run.
validates_attachment_size :avatar,
:less_than => 1.megabytes,
:unless => "avatar.blank?"
You should add similar condition to all validations that affects avatar. If you want know more take a look here.
回答3:
It's more like:
validates_attachment_size :avatar,
:less_than => 1.megabytes,
:unless => "avatar_content_type.blank?"
来源:https://stackoverflow.com/questions/1957752/make-a-field-optional-in-rails