What is the difference between “validate” and “validates” in the rails model?
1 min readDec 26, 2023
Hello friends, In Ruby on Rails, the terms “validate” and “validates” refer to different aspects of the validation process in a model.
validate
(singular):validates
(plural):
validate
(singular):
- The
validate
method in a Rails model is used to specify custom validation methods. - When you use
validate
, you are telling Rails to call a specific method (or multiple methods) during the validation process. These custom validation methods are responsible for checking the validity of the model's data based on your custom criteria. - Example:
validates
(plural):
- The
validates
method is used to apply built-in validation rules to model attributes. - With
validates
, you can specify rules such as presence, length, numericality, and more for individual attributes of the model. - Example:
class MyModel < ApplicationRecord
validates :name, presence: true
validates :email, uniqueness: true, format: { with: /\A[^@\s]+@[^@\s]+\z/ }
end
In summary, validate
is used to define custom validation methods, while validates
is used to apply built-in validation rules to model attributes. Both are essential for ensuring the integrity of data in your Rails application.