我有用户模型和 Controller ,用户有password
、password_confirmation
和password_digest
字段。我使用了 bcrypt
ruby gem。
当我创建用户时,我提供了所有上述字段,然后用户被创建。但用户的密码
不会被保存,它会以十六进制形式保存在password_digest
字段中。
如果我只想编辑用户名,并且当我打开编辑用户表单时,该表单的 password
和 password_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
旨在验证password
和password_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/