Updating `User` attributes without requiring password

前端 未结 9 1649
醉酒成梦
醉酒成梦 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 18:23

    This blog post demonstrates the principal of what you want to do.

    What is not shown, but may be helpful, is to add accessors to the model:

    attr_accessor   :new_password, :new_password_confirmation
    attr_accessible :email, :new_password, :new_password_confirmation
    

    and to provide all of the desired validation under the condition that the user has provided a new password.

      validates :new_password,  :presence => true, 
                                :length   => { :within => 6..40 }, 
                                :confirmation => true, 
                                :if       => :password_changed?
    

    Lastly, I would add a check to see if the encrypted_password has been set in order to determine if "password_changed?" in order to require a password on a new record.

      def password_changed?
        !@new_password.blank? or encrypted_password.blank?
      end
    

提交回复
热议问题