Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails3 + Devise : prevent password validation when updating

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 ?

like image 656
IanBussieres Avatar asked Aug 24 '12 14:08

IanBussieres


1 Answers

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.

like image 191
IanBussieres Avatar answered Oct 02 '22 12:10

IanBussieres