Question

Im going through custom validations in the rails guides (http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations) and im having trouble understanding whats going here. How is the EmailValidator being used? Where is it being called?

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end

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

Like where does all the code go?

Was it helpful?

Solution

you execute validates method passing a hash. When hash is passed, this method iterates over it and for each key it instantiates validator which name matches given key. So if you pass presence: true, it instantiate new instance of PresenceValidator, similarly confirmation: true instantiates ConfirmationValidator. If instead of true, value is a hash, it is being passed to validator and stored there in instance variable @options, which is accessed by options reader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top