ActiveModel::Validations

Prateek vyas
Jul 13, 2022

Ever wondered if you can use ActiveRecord like Validations in a pure ruby class?

ActiveModel::Validations

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
end
teacher = Teacher.new
teacher.first_name = ''
p teacher.valid?
#=> false
p 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 an errors method to your instances initialized with a new ActiveModel::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 :)

--

--

Prateek vyas

Hello i am prateek vyas working as a ruby developer