Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

ruby on rails - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...