Rails3 + Devise: Prevent Password Verification During Upgrade

I am looking for a way to allow users to change their settings (user model) without changing their password (they should still enter their current password). It seems that development out of the box allows this, but when you remove the module being tested and set up custom checks, it seems that you need to work a little.

I installed the following validation in my user model:

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

When registering, the user must specify his password (which I expect). However, when updating the settings, if I leave the password empty, it causes an error for the user who says that the password must be at least 6 characters.

How can I get around this without having to change the way Devise works or the need to implement some kind of user controller?

+5
source share
4 answers

It may be obvious to some, but it took me a while to put it together. After hours of trying various solutions and workarounds and searching all over the place, I went deeper into Rails checks and found several constructs that make this very easy when combined.

All I had to do was set up a check for the create action and one for the update action and allow whitespace for the update.

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

With this, I get the behavior I want, and these are just two short lines of code.

Note:

First I tried this way:

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

, . / ( ?) .

+13

.

private
def password_required?
  new_record? ? super : false
end  
+6

Amal Kumar S, , , , , .

devise/models/validatable.rb

protected

# Checks whether a password is needed or not. For validations only.
# Passwords are always required if it a new record, or if the password
# or confirmation are being set somewhere.
def password_required?
  !persisted? || !password.nil? || !password_confirmation.nil?
end

, , :

!password.nil? || !password_confirmation.nil? 

password password_confirmation '', . , , _required? ? ? .

protected

def password_required?
 !persisted? || !password.blank? || !password_confirmation.blank?
end

, , . , .

+6

update_without_password, , . .

.. , , , , .

:

def update_without_password(params={})
  params.delete(:email)
  super(params)
end

. http://rdoc.info/gems/devise/index

+3

All Articles