Ruby 未定义的方法`密码';对于#<;用户:1123123123>;

Ruby 未定义的方法`密码';对于#<;用户:1123123123>;,ruby,ruby-on-rails-3,forms,model,controller,Ruby,Ruby On Rails 3,Forms,Model,Controller,我将遵循此视频教程,学习如何从头开始创建身份验证: 这是我的用户迁移文件: 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 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 CreateUsers
和我的控制器:

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 UsersController“已注册!”
其他的
呈现“新”
终止
终止
终止
最后是我的模型:

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
class用户

现在,我想我知道为什么会发生这种错误;显然,
@user.save
调用试图将
password
中的值保存到用户表中的password字段,但该字段在数据库中不存在。在视频中,他提到要修复这个bug,我只需将:
attr\u accessible:password
添加到我的模型中,它应该可以工作,但我得到以下错误:

UsersController中的NoMethodError#创建

未定义的方法“密码”#

app/controllers/users\u controller.rb:8:in'create'


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

您有
attr\u可访问:password\u hash,:password\u salt
,但是我认为它应该是
attr\u accessible:password
attr\u accessor:password
一起使用,因为您需要一个虚拟属性
password
,您可以使用
encrypt\u password
方法对其进行操作。因此:

class User < ActiveRecord::Base
  attr_accessible :email, :password
  attr_accessor :password
end
class用户
attr\u accessor
创建虚拟属性,该属性不能作为数据库字段使用(因此为虚拟属性)


attr\u accessible
是一种白名单属性的安全机制,允许通过批量分配来设置这些属性,就像对
User.new(params[:users])
您有
attr\u accessible:password\u hash,:password\u salt
,但是我认为它应该是
attr\u accessible:password
attr\u accessor:password
一起使用,因为您需要一个虚拟属性
password
,您可以使用
encrypt\u password
方法对其进行操作。因此:

class User < ActiveRecord::Base
  attr_accessible :email, :password
  attr_accessor :password
end
class用户
attr\u accessor
创建虚拟属性,该属性不能作为数据库字段使用(因此为虚拟属性)


attr\u accessible
是一种白名单属性的安全机制,可以通过批量分配来设置这些属性,就像你对
User.new(params[:users])
一样。我真是个傻瓜——在仔细写下我的问题后,我注意到我需要使用
attr\u访问器:密码
。哦!我要读一下accessor和accessible之间的区别。我真是个傻瓜——在仔细写下我的问题后,我注意到我需要使用
attr\u accessor:password
。哦!我要读一下accessor和accessible之间的区别。@pduersteler,你能告诉我在rails 4.0中,对于同样的问题,我能做些什么吗?attr_accessible不起作用:(@Emu这也是rails4兼容的。如果它不起作用,您可能会遇到另一个问题。@Emu然后您需要提出一个新问题,并提供足够的代码,以便我们提供帮助。@Pdsteller,您能告诉我在rails 4.0中,对于同样的问题,我能做些什么吗?attr_accessible不起作用:(@Emu这也是rails4兼容的。如果它不工作,您可能会遇到另一个问题。@Emu那么您需要提出一个新问题,并提供足够的代码,以便我们提供帮助。