Disable validation in an object in Ruby on Rails
Posted
by J. Pablo Fernández
on Stack Overflow
See other posts from Stack Overflow
or by J. Pablo Fernández
Published on 2010-04-04T05:15:31Z
Indexed on
2010/04/04
5:23 UTC
Read the original article
Hit count: 253
I have an object which whether validation happens or not should depend on a boolean, or in another way, validation is optional. I haven't found a clean way to do it. What I'm currently doing is this (disclaimer: you cannot unsee, leave this page if you are too sensitive):
def valid?
if perform_validation
super
else
super # Call valid? so that callbacks get called and things like encrypting passwords and generating salt in before_validation actually happen
errors.clear # but then clear the errors
true # and claim ourselves to be valid. This is super hacky!
end
end
Any better ways?
Before you point to the :if argument of many validations, this is for a user model which is using authlogic so it has a lot of validation rules. You can stop reading here if you belive me.
If you don't, authlogic already sets some :ifs like:
:if => :email_changed?
which I have to turn into
:if => Proc.new {|user| user.email_changed? and user.perform_validation}
and in some other cases, since I'm also using authlogic-oid (OpenID) I just don't have control over the :if, authlogic-oid sets it in a way I cannot change it (in time) without further monkey patching. So I have to override seemingly unrelated functions, catch exceptions if a method doesn't exist, etc. The previous hacky solution if the best of my two attempts.
© Stack Overflow or respective owner