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.
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?}
validates :new_pass,:presence => true ,:if => :new_record?
validates :confirmation ,:length =>:within => 6...64, :if => :password_not_blank?
精彩评论