【问题标题】:undefined method `password' for #<User:1123123123>#<User:1123123123> 的未定义方法“密码”
【发布时间】:2013-01-08 14:51:21
【问题描述】:

我正在关注此视频教程并学习如何从头开始创建身份验证:

http://www.youtube.com/watch?v=O5RDisWr_7Q


这是我的用户迁移文件:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :password_hash
      t.string :password_salt

      t.timestamps
    end
  end
end

还有我的控制器:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:users])
    if @user.save
      redirect_to root_url, :notice => "Signed up!"
    else
      render "new"
    end
  end
end

最后是我的模型:

class User < ActiveRecord::Base
  attr_accessible :email, :password_hash, :password_salt

  before_save :encrypt_password

  validates_confirmation_of :password
  validates :password, presence: true
  validates :email, presence: true

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end
end

现在,我想我知道为什么会触发此错误了;显然@user.save 调用试图将password 中的值保存到用户表中的密码字段,但该字段在数据库中不存在。在视频中,他提到要修复此错误,我应该将:attr_accessible :password 添加到我的模型中,它应该可以工作,但我收到以下错误:

UsersController#create 中的 NoMethodError

##的未定义方法“密码”

app/controllers/users_controller.rb:8:in `create'

有什么建议吗?我只是想利用使用强类型模型而不是松散的 html 字段所带来的验证。

【问题讨论】:

  • 我真是个笨蛋——仔细写下我的问题后,我注意到我需要使用attr_accessor :password。哦!我将阅读有关访问器和可访问性之间的区别。

标签: ruby ruby-on-rails-3 forms model controller


【解决方案1】:

你有attr_accessible :password_hash, :password_salt,但我认为它应该是attr_accessible :passwordattr_accessor :password,因为你需要一个虚拟属性password,你在encrypt_password 方法中工作。所以:

class User < ActiveRecord::Base
  attr_accessible :email, :password
  attr_accessor :password
end

attr_accessor 创建的虚拟属性不能用作数据库字段(因此是虚拟的)。

attr_accessible 是一种将属性列入白名单的安全机制,可以像使用User.new(params[:users]) 一样通过批量分配来设置这些属性

【讨论】:

  • @pduersteler,你能告诉我在 Rails 4.0 中我能做什么,同样的问题吗? attr_accessible 不工作:(
  • @Emu 也与 rails4 兼容。如果它不起作用,您可能还有另一个问题。
  • @Emu 那么您需要提出一个新问题并提供足够的代码以便我们提供帮助。
猜你喜欢
  • 2012-05-15
  • 1970-01-01
  • 2011-07-02
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多