【问题标题】:Attribute not Backed by Database not Updating不更新数据库不支持的属性
【发布时间】:2012-02-28 16:51:35
【问题描述】:

我正在尝试为我的 Ruby on Rails 应用程序创建一个 User 模型,该模型具有未保存在数据库中的 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

我正在使用一个非常基本的表单来更新emailpassword

= 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

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

【问题讨论】:

  • 你尝试过 attr_accessible 吗?
  • 什么是attr_accessibleattr 的插件?

标签: ruby-on-rails ruby actioncontroller activeview


【解决方案1】:

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

def password!
  self.password_digest = Digest::SHA1.hexdigest(password)
end

【讨论】:

    猜你喜欢
    • 2011-06-26
    • 2019-10-12
    • 2013-01-17
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    相关资源
    最近更新 更多