[Ruby] rails validation and null: false own memo

1 minute read

Validation is a role like a gatekeeper that is described in the model in advance in order to prevent the value of a specific column sent by the request side from being left empty or being saved in an unintended form.


In the example above,

text “Pass” validates “wait” text “Well” validates “You haven’t entered anything. Redo” text “Pien”

Like this.

On the other hand, what is null: false? Actually, this is also a gatekeeper for not accepting empty data, part 2. null.png

Then, which one is better, I write both, but the correct answer.


The reason is that there is one decisive difference between the above two elements, that is, “the place to protect is different”.

Validation-kun is the gatekeeper in the rails app. It will crack down on submissions from forms. On the other hand, null: false is a gatekeeper waiting in front of the database. This prevents you from writing directly to the database.

A relationship like a bank teller and a security guard in front of a safe. On the contrary, as a result, it is difficult to understand.

If there is no validation, the application will not behave as intended, or if there is no null: false, it will pass through when unintended data is sent to the database in some way.

So, I want you two friends to protect the database.