Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

Understanding Rails validation: what does allow_blank do?

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 :email, :presence => true, :allow_blank => true, :uniqueness => { :case_sensitive => false }

I'm a little bit confused about using presence => true and allow_blank => true together.

Without using allow_blank => true both rules will be checked at the same time and not step by step.

Why does allow_blank => true do this magic?

question from:https://stackoverflow.com/questions/14488465/understanding-rails-validation-what-does-allow-blank-do

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 => {...}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...