Updating `User` attributes without requiring password

前端 未结 9 1662
醉酒成梦
醉酒成梦 2021-01-30 17:27

Right now, users can edit some their attributes without having to enter their password because my validations are set up like this:

validates :password, :prese         


        
9条回答
  •  感情败类
    2021-01-30 18:16

    2017 answer:

    In Rails 5 as also indicated by Michael Hartl's tutorial, it's enought that you have something along these lines in your model:

    validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
    

    allow_nil: true is the key here which allows a user to edit his/her info without also requiring a password change too.

    At this point one might think that this will also allow empty user signups; However this is prevented by using the has_secure_password which automatically validates password presence but only the create method.

    This is a demo User model for illustration purposes:

    class User < ApplicationRecord
      attr_accessor :remember_token
      before_save { self.email = email.downcase }
      validates :name, presence: true, length: { maximum: 50 }
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
      has_secure_password
      validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
      .
      .
      .
    end
    

    I have no clue how to do this with devise. My two cents.

提交回复
热议问题