Search code examples
ruby-on-railsvalidationdrydslskip

How do I stop the others validations to validate when the attribute is not :present in Rails?


What I'm curretly doing is the following:

validates :new_pass,
          :presence => {:if => :new_record?},
          :confirmation => {:if => :password_not_blank?},
          :length => {:within => 6...64, :if => :password_not_blank?}

def password_not_blank?
  !new_pass.blank?
end

But that is not DRY, I bet there is a way to skip the validations if the attribute is not present.

Also, there isn't any DSL method for validating? I think it would be cleaner than implementing logic inside hashes...

-- Edit, thanks ^^ --

This is what I got now:

validates :new_pass,
          :allow_blank => {:on => :update},
          :presence => {:on => :create},
          :confirmation => true,
          :length => {:within => 6...64}

And just for the record and so no one worries (?), this is a virtual attribute, the actual password is encrypted with a before_save, checking that :new_pass is not blank.


Solution

  • The :allow_nil flag for validates might be of interest. Something like this should work:

    validates :new_pass,
              :allow_nil => true,
              :presence => {:if => :new_record?},
              :confirmation => {:if => :password_not_blank?},
              :length => {:within => 6...64, :if => :password_not_blank?}