Don’t validate – Rails

Consider, the situation at the one point of time we want to validate a model, whereas in other situation we should not validate the model. For ex, i’m having two types of ‘events’ type1 and type2. And consider i want to validate a model if it is ‘type1’ event and should not validate if it is ‘type2’ event. It is possible to achieve this scenario in rails.

Here, my model name is “event.rb”. Add the following line to it.

attr_accessor :dont_validate

and consider i validate a presence of field named ‘event_name’
validates_presence_of :name (the code which i done already in model)
modify the above line to,

validates_presence_of :name, :if =>{|x| !x.dont_validate}

Now let’s come to controller (event_controller.rb)

if params[:event][:event_type] == “type1”[:event])
@event.dont_validate = true # avoids validation[:event])

The above code will validate the model if the event type is “type1” and avoid validation for the field ‘name’ for the other type of events(eg.., type2). Remember it just avoid the validation for the ‘name’ field. Incase, if u wanted to avoid validation for other fields you need to specify that in model like this (:if =>{|x| !x.dont_validate}) seperately for each and every validation done in model for which you want to avoid validation.