Ruby on Rails - list validators for a given model

paweldabrowski

Paweł Dąbrowski

Posted on January 3, 2020

Ruby on Rails - list validators for a given model

You can easily list given model validators by calling validators method on the class name:

User.validators # => array of validators

If you define presence validator on your User model:

class User < ActiveRecord::Base
  validates :email, presence: true
end

you can access validator attributes the following way:

email_presence_validator = User.validators.first
email_presence_validator.class # => ActiveRecord::Validations::PresenceValidator
email_presence_validator.attributes # => [:email]
email_presence_validator.options # => {}

The options method returns options like :if or :unless conditions that are passed to the validator definition as extra arguments. Experiment with other types of validations to see how it's working.

Thank you for reading! Follow me on Twitter to be up to date with the latest tips, articles, and videos about programming.

💖 💪 🙅 🚩
paweldabrowski
Paweł Dąbrowski

Posted on January 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related