1

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 2

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I will try that.
Let me know if you have any other question.
If we do that, would the check be at code level or when data goes to database postgres will check?
Validations are typically run before the SQL commands are sent to the database.
@SagarGrover look at my updated answer. I explained this a bit there.
1

You could add the next psql constraints to prevent inserting null or " " strings in your DB without changing an application logics.

CREATE TABLE test (
    string character varying(16) NOT NULL,
    CONSTRAINT good_string CHECK (rtrim(string, ' ') != '')
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.