Understanding Rails validation: what does allow_blank do?

后端 未结 6 1814
一个人的身影
一个人的身影 2020-12-09 01:15

I\'m quite new to Rails and found a little snippet to validate presence and uniqueness step by step: first check presence, then check uniqueness.

validates :         


        
6条回答
  •  天涯浪人
    2020-12-09 02:20

    What you've got is equivalent to this (wrapped for clarity):

    validates :email, :presence => true, 
                :uniqueness => { :allow_blank => true, :case_sensitive => false }
    

    That's a little silly though since if you're requiring presence, then that's going to "invalidate" the :allow_blank clause to :uniqueness.

    It makes more sense when you switch to using other validators.. say... format and uniqueness, but you don't want any checks if it's blank. In this case, adding a "globally applied" :allow_blank makes more sense and DRY's up the code a little bit.

    This...

    validates :email, :format => {:allow_blank => true, ...}, 
                      :uniqueness => {:allow_blank => true, ...}
    

    can be written like:

    validates :email, :allow_blank => true, :format => {...}, :uniqueness => {...}
    

提交回复
热议问题