ruby-on-rails - Rails-无法保存用户密码 bcrypt

标签 ruby-on-rails passwords password-hash bcrypt-ruby

我有用户模型和 Controller ,用户有passwordpassword_confirmationpassword_digest字段。我使用了 bcrypt ruby​​ gem。

当我创建用户时,我提供了所有上述字段,然后用户被创建。但用户的密码不会被保存,它会以十六进制形式保存在password_digest字段中。

如果我只想编辑用户名,并且当我打开编辑用户表单时,该表单的 passwordpassword_confirmation 字段为空。我必须再次提供一个新密码来保存我不想保存的用户。

attr_accessor 没有帮助。

这是我的用户的 Controller :

   before_filter :authorize

   def create
    @user = User.new(user_params)
    if @user.valid?
     @user.password = params[:user][:password]
     @user.password_confirmation = params[:user][:password_confirmation]
     @user.save!
     redirect_to users_path
    else
     flash[:error] = @user.errors.full_message
     render :new
    end
   end

  def edit
   @user = User.find(params[:id])
  end

  def update
   @user = User.find(params[:id])
   if @user.update_attributes(user_params)
    redirect_to user_path
   else
    render 'edit'
    flash[:error] = @user.errors.full_messages
   end
  end

  private
  def user_params
   params.require(:user).permit(:first_name, :last_name, :emp_id, :email, :password, :password_confirmation)
  rescue
  {}
  end

这是我的用户模型:

class User < ApplicationRecord
 rolify
 require 'bcrypt'
 has_secure_password
 # other field validations here....
 validates :password, presence: true
 validates :password_confirmation, presence: true
end

并编辑表单:

<%#= other fields here..... %>
<%= f.label :Password_for_this_portal %>
<%= f.password_field :password, :class=>"form-control" %>
<%= f.label :Confirm_passsword_for_this_portal %>
<%= f.password_field :password_confirmation, :class=>"form-control" %>
# ..... submit button here

如何在编辑用户表单中不再要求更改密码?

最佳答案

has_secure_password 旨在验证passwordpassword_digest。但是,在 Rails 4.x 中,有一个选项可以禁用正在验证的密码:

class User < ApplicationRecord
  has_secure_password :validations => false
end

您可能只能在 create 上执行验证,例如:

 validates :password, presence: true, :on => :create
 validates :password_confirmation, presence: true, :on => :create

关于ruby-on-rails - Rails-无法保存用户密码 bcrypt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42359584/

相关文章:

php - 总是无效的用户名有/没有坏词

php - 无法使用 password_verify($password, $hash)

Java 使用 linux sudo 能力

ruby-on-rails - 在 Ruby on Rails 的 View 模板中从数据库中读取日期是否可以?

ruby-on-rails - Rails 4 - 连接查询匹配数组中的所有内容

ruby-on-rails - rails 3 中的值没有更新

java - 更改 LDAP 用户密码

php - 当我尝试在 symfony 4 中哈希我的密码时,出现这个错误是什么?

java - 如何检查加盐和哈希密码的匹配

ruby-on-rails - 你对使用 Rails 脚手架生成器的看法