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?
Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture. 2.1 Why Use Validations? Validations are used to ensure that only valid data is saved into your database.
To verify whether or not an object is valid, Rails uses the valid? method. You can also use this method on your own. valid? triggers your validations and returns true if no errors were found in the object, and false otherwise. class Person < ActiveRecord::Base validates :name, :presence => true
Since Validator itself obviously does not validate records, let's look at EachValidator, which inherits from Validator. EachValidator implements validate by iterating over an array of attributes, checking each one individually: Here we start to see why Rails uses validator objects internally.
If your validator is complex enough that you want instance variables, you can easily use a plain old Ruby object instead: This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to validates_each will be tested against it.
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 => {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With