I'm trying to figure out the difference between:
validates :foo, presence: false
validates :foo, allow_blank: true
When I use presence: false validation fails but when I use allow_blank: true it does not. According to the docs http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of uses the blank? method. Can someone please explain the difference?
Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.
First case:
validates :foo, presence: false
it does not validate the presence of :foo
at all.
nil, '', 'anything'
are all valid.
Second case: :allow_blank
is an option, not a validator.
It skips validation if the attribute is blank (more here).
If you want to know how it works, you can see the code here.
Before call the selected validator, it checks the attribute is not blank, if it's then skip validation.
The only reason why it works as a validator is the way that source code is written.
At any moment Rails' team can change the code and :allow_blank
stop working as a validator.
allow_blank
only validates nil
, presence
validates nil
as well as empty
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