Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ror
ruby on rails

What is Validation in ROR?

Behzad Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Validation in ROR ensures each active record model class has a valid state. It validates the details entered into the database. In addition to using the built-in validation DSL, we can easily create our own validation methods in ROR.

An error occurs when validation fails. Every Active Record model class has a collection of errors, which is used to display the message when a validation error occurs.

Trigger Validations

We use the following methods to save the objects to the database if they are valid.

  • create

  • create!

  • update

  • update!

  • save

  • save!

The (!) versions raise exceptions if the record is invalid.

Skipping Validations

We use the following methods to skip validations and save the objects to the database regardless of their validity.

  • decrement!

  • decrement_counter

  • increment!

  • increment_counter

  • toggle!

  • touch

  • update_all

  • update_attribute

valid? and invalid?

The valid? triggers your validations and returns true if there is no error. Otherwise, it returns false.

The invalid? is simply the reverse of valid?. It triggers your validations and returns true if invalid. Otherwise, it returns false.

Code

class Student < Record
??validates :name, presence: true
end
?
Student.create(name: "Behzad Ahmad").valid? # => true
Student.create(name: nil).valid? # => false

We have a class Student. In this class, we have to validate the name of the student. To do this, we enter the name of a student and check whether it is valid or invalid. If it is valid then it shows true, and if invalid it shows false.

RELATED TAGS

ror
ruby on rails

CONTRIBUTOR

Behzad Ahmad
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring