Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the presence and allow_blank validators in Rails?

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?

like image 469
Mikhail Janowski Avatar asked Apr 22 '15 12:04

Mikhail Janowski


People also ask

What is validation in Rails?

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.


2 Answers

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.

like image 140
Alejandro Babio Avatar answered Sep 30 '22 17:09

Alejandro Babio


allow_blank only validates nil, presence validates nil as well as empty

like image 28
jon snow Avatar answered Sep 30 '22 15:09

jon snow