Programmatically disabling validates_presence_of for an instance of a model.

I have a number of models with various data validations, e.g:

class Task < ActiveRecord::Base

  validates_presence_of :comment   validates_presence_of :complaint   validates_inclusion_of :status, :in => TASK_STATUSES   validates_format_of :policy_number...

[...]

end

A user is allowed to save data in an incomplete state, which currently disables all validations for the model. Not good. What I want to do is programmatically disable validates_presence_of for the duration of the save on *that instance of the model alone*, whilst still allowing the other data format validations to be processed - i.e. temporarily overriding a class method with an instance method, or aliasing the class method with another class method that checks an instance variable to determine whether or not to proceed with the call to validates_presence_of.

What I read on the web left me a little confused as to issues such as thread-safety, etc.

Any suggestions?

I'm not sure I understad what you're requesting, but you should be able to do something like

validates_presence_of :comment, :if => Proc.new { |task| !task.draft }

In the above, "task" is the current model instance you're trying to save. I don't think there would be any threading issues...

Hey Nick,

I wrote a plugin [1] that might help you out. It doesn't let you disable a particular validation, but it lets you define a new set of validations on an instance. So you could define all validations except for that v_p_o.

Pat

[1] eli.st

Thanks for the feedback guys. I was aware of the :if condition on the validates_* methods, but wanted to avoid maintaining those across a number of models and a large number of validations.

The idea is to dynamically disable validates_presence_of at the start of the "save incomplete" call. And re-enable it once the save is complete.

Thanks for the link Pat, I'll check it out.