2009-12-24 55 views
2

我使用回形针将头像附加到用户上,这种方式很好,但是当新用户尝试注册时,它抱怨头像太小而不是正确的类型。在栏杆中设置栏位可选

这是我如何验证我的头像:

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 

是否有无论如何使头像可以是空白?

回答

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? 
+0

我用 “:除非=>:new_user?”并写了一个函数返回true/false似乎已经修复它 – Arcath 2009-12-24 12:32:38

+0

:if => avatar_file_name_changed?为我工作 – 2011-08-17 07:20:40

1

我没有用曲别针,但一般在Rails中,你可以添加条件,以决定是否验证应运行。

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

您应该为影响化身的所有验证添加类似的条件。如果你想知道更多看看here

0

它更像是:

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