在rails中创建一个可选字段

时间:2009-12-24 10:27:38

标签: ruby-on-rails paperclip

我使用paperclip将头像附加到用户,这可以正常工作,但是当新用户尝试注册时,会抱怨头像太小而且类型不合适。

这是我验证我的头像的方式:

validates_attachment_size :avatar, :less_than => 1.megabytes
validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png', 'image/gif']

这是我尝试注册时遇到的错误。

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

无论如何都是为了使头像可以为空?

3 个答案:

答案 0 :(得分:2)

我不知道这是否会奏效但是尝试:

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?

答案 1 :(得分:1)

我没有使用paperclip,但通常在Rails中你可以添加条件来决定是否应该运行验证。

validates_attachment_size :avatar, 
  :less_than => 1.megabytes, 
  :unless => "avatar.blank?"

您应该为影响头像的所有验证添加类似的条件。如果您想了解更多,请查看here

答案 2 :(得分:0)

更像是:

validates_attachment_size :avatar, :less_than => 1.megabytes, :unless => "avatar_content_type.blank?"