Rails3 + Devise : prevent password validation when updating

前端 未结 4 1355
Happy的楠姐
Happy的楠姐 2021-01-01 00:23

I\'ve looking for a way to allow users to change their settings (User model) without having to change their password (they still have to enter their current password). Devis

4条回答
  •  自闭症患者
    2021-01-01 01:09

    Maybe this will look obvious for some, but it took me a while getting this together. After a few hours of trying different solutions and workarounds and looking all over the place, I dove deeper in Rails validations and found a few constructs that, when put together, make this really easy.

    All I had to do was setup a validation for the create action and one for the update action and allow blanks on update.

      validates :password, length: { in: 6..128 }, on: :create
      validates :password, length: { in: 6..128 }, on: :update, allow_blank: true
    

    With that, I'm getting the behaviour I want and it's only two short lines of code.

    Additional note :

    At first, I had tried this way :

    validates :password, length: { in: 6..128 }, on: :create
    

    This is wrong because it would skip the validation entirely on updates. Users would then be able to set short/long (or blank?) passwords when updating settings.

提交回复
热议问题