In Rails 3, how can I skip validation of the password field when I'm not attempting to update the password?

后端 未结 5 374
臣服心动
臣服心动 2020-12-05 10:31

My User model contains :name, :email, and :password fields. All 3 have validations for length. An \"update account\" web page allows the user to update his name and email

相关标签:
5条回答
  • 2020-12-05 11:19

    My application does something like this

    attr_accessor :updating_password
    
    validates_confirmation_of :password, :if => should_validate_password?
    
    def should_validate_password?
      updating_password || new_record?
    end
    

    so you have to model.updating_password = true for the verification to take place, and you don't have to do this on creation.

    Which I found at a good railscast at http://railscasts.com/episodes/41-conditional-validations

    0 讨论(0)
  • 2020-12-05 11:19

    In your user model, you could just ignore the password validation if it's not set.

    validates_length_of :password, :minimum => N, :unless => lambda {|u| u.password.nil? }
    
    0 讨论(0)
  • 2020-12-05 11:28

    Using update_attributes will not change the value of the password if there is no key for it in the params hash.

    Validation doesn't run against the changed fields only. It validates existing values too.

    Your validation must be failing because the password field contains some invalid content that's already saved in the database. I'm guessing it's probably because you're hashing it after validation and you're trying to validate the hashed string.

    You can use a virtual attribute (an instance variable or method) that you validate with a custom method, and then assign the hash to the stored password field. Have a look at this technique for ideas.

    0 讨论(0)
  • 2020-12-05 11:32

    An app that I am working on uses the following:

        validates_confirmation_of :password, 
                                  :if => Proc.new { |account| 
                                                    !account.password.blank? 
                                                    || !account.password_confirmation.blank? 
                                                    || account.new_record? }
    

    Depending on your requirements, you might want to remove the new_record? check

    0 讨论(0)
  • 2020-12-05 11:32
    When password is added then only confirmation will be called and presence will call on create action only   
    
       **validates_presence_of :password, :on =>:create**
    
       **validates_confirmation_of :password**
    
    0 讨论(0)
提交回复
热议问题