我正在尝试为我的User
应用创建一个Ruby on Rails
模型,其中password
字段未保存在数据库中,但出于某种原因,它尚未更新正确。
class User < ActiveRecord::Base
attr :password
validates_presence_of :email, :password_digest
def password!
password_digest = Digest::SHA1.hexdigest(password)
end
def password?(password)
password_digest == Digest::SHA1.hexdigest(password)
end
end
我正在使用非常基本的表单来更新email
和password
。
= form_for @user do |f|
-if @user.errors.any?
#error_explanation
%h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
%ul
- @user.errors.full_messages.each do |msg|
%li= msg
.field
= f.label :email
= f.email_field :email, :required => true
.field
= f.label :password
= f.password_field :password, :required => true
.actions
= f.submit 'Save'
在我的控制器中,我正在尝试使用基本的更新机制,但如果我绝对需要,我愿意添加更多代码。
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.password!
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
end
处理此更新时,会抛出TypeError
,并显示以下消息:can't convert nil into String
。
我尝试了几种不同的方法来解决此问题,包括使用password
手动设置params[:user][:password]
但不起作用。谁能发现我错过的错误?
答案 0 :(得分:2)
在您的密码中!方法,您需要指定要访问实例变量password_digest。改为:
def password!
self.password_digest = Digest::SHA1.hexdigest(password)
end