0

我正在尝试为我的应用程序创建一个User模型,该模型具有未保存在数据库中的字段,但由于某种原因,它没有被正确更新。Ruby on Railspassword

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

我正在使用一个非常基本的形式来更新emailand 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

我尝试了几种不同的方法来解决这个问题,包括手动设置passwordusingparams[:user][:password]但它不起作用。谁能发现我错过的错误?

4

1 回答 1

2

在你的密码!方法,您需要指定要访问实例变量 password_digest。改成:

def password!
  self.password_digest = Digest::SHA1.hexdigest(password)
end
于 2012-02-28T16:58:11.723 回答