Make a field optional in rails

≡放荡痞女 提交于 2019-12-20 03:26:13

问题


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

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