문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top