Rails:更新用户但密码无效

时间:2013-11-11 16:43:18

标签: ruby-on-rails ruby

我有付款API,可以获取银行帐户信息和用户信息。我抓住api响应并使用ajax将信息发送到我的控制器,在那里我尝试将信息保存到我的用户。当我保存时,我收到错误Validation failed: Password can't be blank, Password is invalid:有任何想法吗?

银行控制员:

def addbank
  @user = current_user
  @user.phone_number = params[:phone_number]
  @user.birth_year = params[:year]
  @user.bank_uri = (params['bank_acct_uri'])
  @user.save! # <------- ERROR here!
  # Code was removed to be more clear
end

用户控制器:

def update
  # update user controller has been commented out but the error is still there
end

用户模型:

class User < ActiveRecord::Base
attr_accessible :email,:password,:password_confirmation,:phone_number,:birth_year

      attr_accessor :password
      before_save :encrypt_password
      before_save { |user| user.email = email.downcase }

      VALID_PASSWORD_REGEX = # some reg-expression
      VALID_PHONE = # some reg-expression
      validates_confirmation_of :password
      validates :password, presence: true, format:{  with: VALID_PASSWORD_REGEX }
      validates :phone_number, format: { with: VALID_PHONE }, if: :phone_number
end

编辑:为什么保存用户没有点击我的更新用户控制器?

4 个答案:

答案 0 :(得分:2)

如果您想避免验证某个特定字段(在您的情况下为密码),但您想要进行所有其他验证(例如电话号码),您可以执行以下操作:

attr_accessor :skip_password

validates :password, presence: true, format:{  with: VALID_PASSWORD_REGEX }, unless: :skip_password

然后,在你的控制器中,你可以这样做:

def addbank
  @user = current_user
  @user.skip_password = true # We don't want to validate this..
  @user.phone_number = params[:phone_number]
  @user.birth_year = params[:year]
  @user.bank_uri = (params['bank_acct_uri'])
  @user.save! # <------- ERROR here!
  # Code was removed to be more clear
end

这样做需要您自担风险~~

答案 1 :(得分:1)

您可以尝试保存而无需验证:

@user.save(:validate => false)

更新:

if !@user.valid? && @user.errors[:phone_number].any?
  #do not save
else
 @user.save(:validate => false)
end

答案 2 :(得分:1)

您在哪里存储加密密码?

如果您将其存储在password中,那么每次保存都会失败,因为它不等于password_confirmation

我建议将密码放在一个单独的字段中。

#from the User Model
attr_accessor :password, :password_confirmation

validates_presence_of :password, :on => :create
validates_confirmation_of :password

def password=(password)
    @password = password
    self.password_digest = BCrypt::Password.create(@password, :cost => 14)
end

def authenticate(password)
    BCrypt::Password.new(self.password_digest) == password
end

这样,密码会被哈希并保存到password_digest,并且在保存时不会触发验证错误。

答案 3 :(得分:0)

我会发布这个,因为我大约95%确定这是原因,但如果我离开,我会道歉。

我认为原因是因为用户的密码确实是空白的。如果您查看数据库,您会看到一个名为encrypted_password的列,它永远不会通过您的模型直接访问,也不会被解密到您的可访问password和{{1} } attributes。

要更新用户,您必须输入重新输入密码,或使用password_confirmation方法(可能危险地)绕过验证。