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.
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.
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
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.
class Student < Record??validates :name, presence: trueend?Student.create(name: "Behzad Ahmad").valid? # => trueStudent.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.
Free Resources