Updating `User` attributes without requiring password

前端 未结 9 1651
醉酒成梦
醉酒成梦 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:14

    I've been struggling with this and going around in circles for a while, so I thought I'd put my Rails 4 solution here.

    None of the answers I've seen so far meet my use case, they all seem to involve bypassing validation in some way, but I want to be able to validate the other fields and also the password (if present). Also I'm not using devise on my project so i can't make use of anything particular to that.

    Worth pointing out that it's a 2 part problem:

    Step 1 - you need to remove the password and confirmation field from the strong parameters if the password is blank like so in your controller:

    if myparams[:password].blank?
      myparams.delete(:password)
      myparams.delete(:password_confirmation)
    end
    

    Step 2 - you need to alter validation such that the password isn't validated if it's not entered. What we don't want is for it to be set to blank, hence why we removed it from our parameters earlier.

    In my case this means having this as the validation in my model:

    validates :password, :presence => true, :confirmation => true, length: {minimum: 7}, :if => :password
    

    Note the :if => :password - skip checking if the password is not being set.

提交回复
热议问题