This is more of a conceptual doubt. Is there any way in which we can apply a constraint that value of a field can't be blank? I know NOT NULL can be used. But I want to check if the field has only spaces, it rejects that value also. For example " " should be rejected.
2 Answers
In your Model's class, you can add a validation like this:
validates :field_name, presence: true
From the Rails Documentation:
This helper validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.
That will ensure that the value of that field can't be blank.
When validations are run?
Creating and saving a new record will send an SQL INSERT operation to the database. Updating an existing record will send an SQL UPDATE operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation. This avoids storing an invalid object in the database.
See this for more details.
5 Comments
SQL commands are sent to the database.