且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails3 + Devise:更新时防止密码验证

更新时间:2022-10-14 23:40:01

也许这对于某些人来说看起来很明显,但是我花了一段时间才能得到这些。经过几个小时的尝试,不同的解决方案和解决方法,并且遍及整个地方,我深入研究了Rails的验证,并发现了几个结构,当它们放在一起时,使其变得非常简单。



所有我需要做的是为创建操作设置验证,并为更新操作设置一个验证,并允许更新的空白。

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

这样,我得到了我想要的行为,只有两行短的代码。 p>

附加说明:



起初,我试过这样:

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

这是错误的,因为它将完全跳过验证更新。用户可以在更新设置时设置短/长(或空白)密码。


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). Devise out of the box seems to allow this, but when you remove the validatable module and setup custom validations, it seems you need to work around a bit.

I have setup the following validation in my user model :

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

When signing up, user is required to specify his password (which is what I expect). When updating settings, though, if I leave password blank it raises an error to the user that says password must be at least 6 characters.

How can I work around this without having to change the way Devise works or having to implement a custom controller of some sort ?

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.