ActiveModel::Validations
Jul 13, 2022
Ever wondered if you can use ActiveRecord like Validations in a pure ruby class?
ActiveModel::Validations provides a full validation framework to your objects.
Let’s look at the basic implementation
class Teacher
include ActiveModel::Validations
attr_accessor :first_name, :last_name
validates :first_name, presence: true
endteacher = Teacher.new
teacher.first_name = ''p teacher.valid?
#=> falsep teacher.errors
#=>#<ActiveModel::Errors [#<ActiveModel::Error attribute=first_name, type=blank, options={}>]>p teacher.errors.messages
#=> {:first_name=>["can't be blank"]}
ActiveModel::Validations
automatically adds anerrors
method to your instances initialized with a newActiveModel::Errors
object, so there is no need for you to do this manually
Methods provided by ActiveModel::Validations are:-
Thanks for giving it a read!
Happy coding :)