Sandeep Rao
Sandeep Rao

Reputation: 1757

skip some validations during creation in rails, but have other validations run

I want to skip the validations of few attributes during creation of a new user like address, pin, phone number etc.
However, it still need to do the other validations in the model when user tries to edit it. I tried using :on => :update but that doesn't help me. Any suggestions ?

My Code:

validates :address, :presence => true, :length => { :maximum => 50 }, :on => :update 
validates :city, :presence => true, :length => { :maximum => 50 }, :on => :update 
validates :state, :presence => true, :length => { :maximum => 50 }, :on => :update 
validates :zip, :presence => true, :numericality => true, :on => :update, :length => { :is => 5 }

Upvotes: 0

Views: 1867

Answers (4)

Sandeep Rao
Sandeep Rao

Reputation: 1757

validates :address, :presence => true,
                      :length => { :maximum => 50 },
                      :if => :address_changed?

  validates :city, :presence => true,
                   :length => { :maximum => 50 },
                   :if => :city_changed?

  validates :state, :presence => true,
                    :length => { :maximum => 50 },
                    :if => :state_changed?

  validates :zip,   :presence => true,
                    :numericality => true,
                    :length => { :is => 5 },
                    :if => :zip_changed?

Adding if=> :attribute_changed? will solve the problem.

Upvotes: 2

Michael Durrant
Michael Durrant

Reputation: 96474

The validation process on save can be skipped by passing :validate => false.

Note that is there are database constraints you'll still get an error. e.g. if you use a rails migration and have :null => false when it is created (by running the migration) the actual database column will have that restriction be at the database level. A good thing as validations should be in both places. The way to override the db constrainst (i.e. you can't) would be a migration to actually remove the constraint.

Upvotes: 4

Jak
Jak

Reputation: 3233

On creation of record:

@model = Model.new(params[:model])
@model.save false

This will skip the validation.

Upvotes: 2

Justin Herrick
Justin Herrick

Reputation: 3011

According the the documentation, what you need to do is something like this. Are you saying this is not working?

class Person < ActiveRecord::Base
  validates_presence_of :address, :on => :update
  validates_presence_of :pin,     :on => :update
end

Upvotes: 5

Related Questions