2017-02-21 41 views
1

我有用户模型和控制器,用户有password,password_confirmationpassword_digest字段。我曾用bcrypt红宝石宝石。Rails-无法保存用户密码bcrypt

当我创建用户时,我提供了上述所有字段并创建了用户。但用户的password不会被保存,它将以十六进制格式保存在password_digest字段中。

如果我想编辑只是用户的名字,当我打开编辑用户表单时,表格有passwordpassword_confirmation字段为空。我不得不再次给一个新的密码来保存我不想要的用户。

attr_accessor没有帮助。

这里是我的用户的控制器:

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 

如何不为编辑密码更改再问用户表单?

+0

这就是它的应该工作,你不会将密码保存在数据库中。它出于安全原因被保存为摘要。 – trueinViso

+0

你永远不会保存实际的密码,只能摘要。这样,如果你的数据库被黑客攻击,黑客就无法恢复用户密码来推断其他服务的密码。 – Maxence

回答

1

has_secure_password旨在验证passwordpassword_digest。然而,在Rails的4.x中,有一个选项来禁用password与被验证:

class User < ApplicationRecord 
    has_secure_password :validations => false 
end 

你可能只能够在create进行验证,如:

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

谢谢香农,如果我想验证两种方法,说:“删除”和“创建”,“:开”不适用于两种方法。 – suhasa