Validates presence vs null false in Rails models / tables

I played with the Rails administrator and I noticed something.

Attributes that are defined in the model below are considered “Required” in Rails admin

validates :user, presence: true 

However, the attributes defined in the table below (schema / migration) are still considered “optional”

 t.datetime "created_at",:null => false 

I would suggest that they are both identical, with the possible exception of the level from which the validation error pops up. Am I mistaken or is this a Rails admin error? Both of them guarantee that this field will be required for successful storage in the field or is there a difference?

+6
source share
2 answers

Addition :null => false means that this is a database limitation, i.e. under no circumstances does the database allow a null value.

Adding presence: true is a model level check, so it happens before the object is inserted into the database. There may be times when you want to break these checks (for example, cases with an edge or in your specifications). Then you can skip the check with :validates => false , and the object will still go to the database with a zero database restriction, this will not happen.

+7
source
 t.datetime "created_at",:null => false 

tells the database that it does not accept null values. Whereas validates :user, presence: true it looks like the Rails application does not accept null values. But it would be nice if they were integrated, for example, to have: null => false, so that it also registered Rails to validate the model.

+2
source

Source: https://habr.com/ru/post/958053/


All Articles