Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

skip certain validation method in Model

I am using Rails v2.3

If I have a model:

class car < ActiveRecord::Base

  validate :method_1, :method_2, :method_3

  ...
  # custom validation methods
  def method_1
    ...
  end

  def method_2
    ...
  end

  def method_3
    ...
  end
end

As you see above, I have 3 custom validation methods, and I use them for model validation.

If I have another method in this model class which save an new instance of the model like following:

# "flag" here is NOT a DB based attribute
def save_special_car flag
   new_car=Car.new(...)

   new_car.save #how to skip validation method_2 if flag==true
end

I would like to skip the validation of method_2 in this particular method for saving new car, how to skip the certain validation method?

like image 399
Leem.fin Avatar asked Jan 16 '12 14:01

Leem.fin


3 Answers

Update your model to this

class Car < ActiveRecord::Base

  # depending on how you deal with mass-assignment
  # protection in newer Rails versions,
  # you might want to uncomment this line
  # 
  # attr_accessible :skip_method_2

  attr_accessor :skip_method_2 

  validate :method_1, :method_3
  validate :method_2, unless: :skip_method_2

  private # encapsulation is cool, so we are cool

    # custom validation methods
    def method_1
      # ...
    end

    def method_2
      # ...
    end

    def method_3
      # ...
    end
end

Then in your controller put:

def save_special_car
   new_car=Car.new(skip_method_2: true)
   new_car.save
end

If you're getting :flag via params variable in your controller, you can use

def save_special_car
   new_car=Car.new(skip_method_2: params[:flag].present?)
   new_car.save
end
like image 195
shime Avatar answered Oct 01 '22 14:10

shime


The basic usage of conditional validation is:

class Car < ActiveRecord::Base

  validate :method_1
  validate :method_2, :if => :perform_validation?
  validate :method_3, :unless => :skip_validation?

  def perform_validation?
    # check some condition
  end

  def skip_validation?
    # check some condition
  end

  # ... actual validation methods omitted
end

Check out the docs for more details.

Adjusting it to your screnario:

class Car < ActiveRecord::Base

  validate :method_1, :method_3
  validate :method_2, :unless => :flag?

  attr_accessor :flag

  def flag?
    @flag
  end    

  # ... actual validation methods omitted
end

car = Car.new(...)
car.flag = true
car.save
like image 44
Michał Szajbe Avatar answered Oct 01 '22 12:10

Michał Szajbe


Another technique, which applies more to a migration script than application code, is to redefine the validation method to not do anything:

def save_special_car
   new_car=Car.new
   new_car.define_singleton_method(:method_2) {}
   new_car.save
end

#method_2 is now redefined to do nothing on the instance new_car.

like image 24
fkoessler Avatar answered Oct 01 '22 13:10

fkoessler