我在我的用户模型中有这个代码:
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
validates :email, :presence => true,
:uniqueness => { :case_sensitive => false },
:format => { :with => /\A[^@]+@[^@]+\z/ },
:length => 7..128
validates :password, :presence => true,
:confirmation => true,
:length => 6..128
private
def encrypt_password
return unless password
self.encrypted_password = BCrypt::Password.create(password)
end
end
Run Code Online (Sandbox Code Playgroud)
现在在我的控制器中,当我用一些用户字段更新时
@user.update_attributes(params[:user])
Run Code Online (Sandbox Code Playgroud)
即使没有在params散列中设置密码字段,也始终验证密码字段.我认为这是因为attr_accesor:密码总是在update_attributes上设置password ="".
现在我可以简单地跳过验证密码,如果它是一个空字符串:
validates :password, :presence => true,
:confirmation => true,
:length => 6..128,
:if => "password.present?"
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为它允许用户设置一个空密码.
在我想要更改的字段上使用update_attribute不是解决方案,因为我需要对该属性进行验证.如果我传入确切的参数
@user.update_attributes(params[:user][:fieldname])
Run Code Online (Sandbox Code Playgroud)
它不能解决问题,因为它还会触发密码验证. …