Monday, 3 August 2015

How to skip rails validation



Skip all validations:

validates :name, presence: true

@user.name = ""
@user.save(validate: false)

It saves the record without running any validations.

Skipping individual validations:

Skipping individual validations requires a bit more work. First, we need to create a property on our model called something like skip_name_validation:

attr_accessor :skip_name_validation, :skip_price_validation

Next we will tell Rails to check and see if that property is set to true:

validates :name, presence: true, uniqueness: true, unless: :skip_name_validation
Validates: price, presence: true, numerically: {greater_than: 0 }, unless: :skip_price_validation

Finally we will set the property to true any time we want to skip validations. For example:

def create
   @product = Product.new(product_params)
   @product.skip_name_validation = true
   if @product.save
    redirect_to products_path, notice: "#{@product.name} has been created."
  else
    render 'new'
  end
end

def update
  @product = Product.find(params[:id])
  @product.attributes = product_params
  @product.skip_price_validation = true
  if @product.save
    redirect_to products_path, notice: "The product \"#{@product.name}\" has been updated. "
  else
    render 'edit'
  end
end

Above you will see that for the create method we skip name validation; and for the update method we skip price validation. A complete listing of the model is shown below.

class Product < ActiveRecord::Base
  validates :name, presence: true, uniqueness: true, unless: :skip_name_validation
  validates :price, presence: true, numericality: { greater_than: 0 }, unless: :skip_price_validation

  attr_accessor :skip_name_validation, :skip_price_validation
end
That's it...:-)


No comments:

Post a Comment