Active Record Validation in Rails Part I

Tram Ho

Surely when you work and manipulate data, what we care about most is their correctness. Although you have given instructions, for example to users so that they can enter, there are still cases due to the ability to read and understand, deliberately mistakenly write to make errors or for some spiritual reason that the data entered The input does not match the desired system format, causing our database to “lose its purity”. To prevent this, Rails has provided an extremely powerful “tool” that I want to share with you in this article: Active Record Validations

When do Validations take place?

As mentioned above, Validations are built into Rails and automatically implemented when there is a change directly related to the record. Simply put, when we save or update a record, the magic tool will unleash its power. Our only job is to call it out as a bodyguard for the database only. Let’s gooo!

Validation Helpers

Active Record provides many validation methods for performing common validates. All of these methods can handle multiple fields and have 2 options. Where : on will specify when validates are performed (there are 2 values : create and : update ). Option 2 is : message to specify the error message when validates an error (if not used, the message will have a default value according to Rails written for each helper). Now we will point out the specific bright candidates that Active Record brings offline:

  • accept

    This method will check if the checkbox is checked or not when the form is submitted. It is often used when the user needs to agree to a terms of operation, or reconfirm some text that needs to be read. When you want to have a value other than nil with a checkbox with name = “check_it” we just need to use it:
    validates: :ckeck_it, acceptance: true

  • validates_associated

We should use this when the model is linked to another model and they need to be verified. When we try to save the object into the database, valid? will be called in every object associated with it.

This authentication works for all types of links. Note: do not use validates_associated on both sides of the link. If we do that, an eternal loop will be created.

  • confirmation

This third candidate works to test whether two text fields are of equal value. For example, when confirming a password when registering, this authentication will create a virtual attribute, with the name of the attribute appended with “_confirmation”.

In the view, there is a form with password_confirmation field

Now the simple password check cannot be stopped.

  • exclusion

The exclusion verifies that the value of the attribute is not within a given set. For example, if you don’t want the “am_i_handsome” field to be “no”, you can simply apply it as follows:

The exclusion method has an option: print. Which will contain a set of invalid values. Optional : print has an alias that is : within . This property also has the same function as : print . The default message is “is reserved”.

  • inclusion

In contrast to the exclusion this method validates the value of the attribute that must be in a given set.

The inclusion helper has an option of : print will only allow valid values ​​to be included. This option has an alias : within that works the same way. The default message is “is not included in the list”

  • format

This helper will validate attribute values ​​by performing a check to see if a regular expression is satisfied. Options used are : with :

The default message is: “is invalid”

  • length

The last candidate introduced in this article is capable of checking the length of attribute values. It will provide a number of options that we can use flexibly:

Available options include:

: minimum – The property cannot have less than values ​​set.

: maximum – An attribute cannot have more than a value set.

: in (or : within ) – The length of the value of the attribute must be within a certain range.

: is The length of the attribute must be equal to the specified value.

The default error message depends on the length of the validation being executed. We can customize it using the options : wrong_length ,: too_long ,: too_short and % {count} .

We can still use the : message option to set up an error message like the helper introduced above.

valid? and invalid?

As introduced, Validates will take place automatically if we want to actively perform data validation? Rest assured because Rails has thoughtfully retrofitted us with two invalid methods ? and valid? . We can run validations by ourselves. Validation method ? Will allow us to do this. It will return true if no error has been generated and false otherwise. For example:

After the Active Record executes validations, we can find error validations in the instance method errors.messages.

By default, an object will be considered valid if errors.messages return empty after running validations. Note that an object initialized with the new method will not generate an error even if it is invalid , because validation only runs when the object is saved , for example when implementing the create , save methods.

Method invalid? is the opposite of valid? .


Through this part, you can see the importance of Active Record Validations in helping us manipulate and deal with data. Taking advantage and promoting the strengths that Active Record Validations brings will help your system to be more complete and professional.

Thank you for reading the article, see you again in Part II ^. ^

Share the news now

Source : Viblo