I've got a model Officer that relies on password validation in all
cases, but I need it to validate the password at different times. For
on create, I want to verify that the password and password
confirmation exists at all times. For update, want to make it
possible for providing password optional, and only when the password
is provided, to make sure it matches the password confirmation and the
within a certain length (such as when calling method
update_attributes).
The best ways I see it right now is to define either
before_validation_on_create, after_validation_on_create, or
before_create for method new, and define either
before_validation_on_update, after_validation_on_update, or
before_update for method update_attributes. It's worth noting that
Officer extends off of Person, which has it's own validations to do.
I have several questions about this. First, which function should I
define for validating create and update? What are the pros and cons
on each one?
I've also noticed that I cannot use validate_length_of and other
helper methods inside these, and wondered why I'm not allowed to.
Does this mean I have to make my own validation?
If I do have to make my own validations within these methods, I will
have to verify that the pseudo-parameters :password
and :password_confirmation exists. Do I have to call attr_accessor on
either :password, :password_confirmation, or both in this case?
Many thanks in advance!
P.S. Currently, my Officer and Person model looks like this:
where :userEmail is the HTML input, and PrivilegedUser is the name
of the class.
(3) For passwords, and other validations that require some custom logic,
add a "validate" method to your class. ActiveRecord will call this
automatically. Let's assume your HTML inputs are pswd and verify_pswd:
def validate
# this disallows empty values if the record is new
if self.new_record? && (@pswd.blank? || @verify_pswd.blank?)
self.errors.add(:pswd, 'Password cannot be empty.')
end