使用restful_authentication插件时,进行更新密码操作时,如果传来密码为空时,会发现有关密码验证空值验证会失效
这是因为在
by_password.rb文件中,是这样记录的
# Stuff directives into including module
def self.included(recipient)
recipient.extend(ModelClassMethods)
recipient.class_eval do
include ModelInstanceMethods
# Virtual attribute for the unencrypted password
attr_accessor :password
validates_presence_of :password, :if => :password_required?
validates_presence_of :password_confirmation, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?
validates_length_of :password, :within => 6..40, :if => :password_required?
before_save :encrypt_password
end
end # #included directives
def password_required?
crypted_password.blank? || !password.blank?
end
此时crypted_password存在, crypted_password.blank?返回false, 而!password.blank?也返回false
所以password空值验证就失效了
validates_presence_of :password, :if => :password_required?
解决这个问题可以在更新之前,把crypted_password设置成nil
@user = User.find_by_id(params[:id])
@user.crypted_password = nil
if @user.update_attributes(:password => params[:password], :password_confirmation => params[:password_confirmation])
flash.now[:notice] = "success"
else
flash.now[:notice] = "error"
end