3

In my user model i have validation of password and an instance method like this:

class User < ActiveRecord::Base
  validate :email ......
  validates :password, length: { minimum: 6 }

  def my_method
    # .....
    # save!
  end
end

As you can see inside this method i have a call to the save! method which save the user after altering some fields, so i want to skip the validation of password but not other validations only when i call my_method on a user instance , how i can do this please ? thank you

medBouzid
  • 7,484
  • 10
  • 56
  • 86

2 Answers2

3

I find the solution if someone is interesting, i simply add attr_accessor :skip_password_validation to my model, then i add a condition to my password validation validates :password, length: { minimum: 6 }, unless: :skip_password_validation, and when i call my_method in the controller with an instance of user model, i set this attribute above with true. it's all , here what the user model will look like:

class User < ActiveRecord::Base
  validate :email ......
  validates :password, length: { minimum: 6 }, unless: :skip_password_validation
  attr_accessor :skip_password_validation

  def my_method
    # .....
    # save!
  end
end

In the controller before i call user.my_method i just add the line : user.skip_password_validation = true.

I hope this help you :)

medBouzid
  • 7,484
  • 10
  • 56
  • 86
-3

You can do it with 2 methods.

model.save(:validate => false)

See here and here

OR

Skipping the Callback

skip_callback :validate, :before, :check_membership, :if => lambda { self.age > 18 }

API Doc

Community
  • 1
  • 1
Althaf Hameez
  • 1,511
  • 1
  • 10
  • 18
  • :validate => false will skip all other validations, i want just skip password validation – medBouzid Aug 11 '13 at 14:04
  • 2
    Oh right. Then you might want to take a look at [this](http://stackoverflow.com/questions/3542819/in-rails-3-how-can-i-skip-validation-of-the-password-field-when-im-not-attempt) – Althaf Hameez Aug 11 '13 at 14:08