代码之家  ›  专栏  ›  技术社区  ›  Arcath

在Rails中使字段可选

  •  2
  • Arcath  · 技术社区  · 16 年前

    我使用回形针将虚拟人物附加到用户身上,这很好,但是当一个新用户试图注册时,它会抱怨虚拟人物Bieng太小,类型不正确。

    这就是我如何验证我的化身:

    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 回复  |  直到 16 年前
        1
  •  2
  •   khelll    16 年前

    我不知道这是否可行,但尝试一下:

    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
  •  1
  •   klew    16 年前

    我没有使用回形针,但一般来说,在Rails中,您可以添加条件来决定是否应该运行验证。

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

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

        3
  •  0
  •   Tiago Franco    16 年前

    它更像:

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