## User:1123123123>的未定义方法`password'

ser*_*erg 1 ruby forms controller model ruby-on-rails-3

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

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
Run Code Online (Sandbox Code Playgroud)

而我的控制器:

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
Run Code Online (Sandbox Code Playgroud)

最后我的模型:

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
Run Code Online (Sandbox Code Playgroud)

现在,我想我知道为什么这个错误会被解雇; 很明显,该@user.save调用试图将值保存password到User表中的password字段中,但该字段在数据库中不存在.在视频中他提到要修复这个bug,我应该添加:attr_accessible :password到我的模型,它应该工作,但我收到以下错误:

UsersController中的NoMethodError #create

#的未定义方法`密码'

app/controllers/users_controller.rb:8:在'create'中

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

pdu*_*ler 5

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

class User < ActiveRecord::Base
  attr_accessible :email, :password
  attr_accessor :password
end
Run Code Online (Sandbox Code Playgroud)

attr_accessor 创建虚拟属性,该属性不可用作数据库字段(因此是虚拟的).

attr_accessible 白名单属性的安全机制,允许通过大量分配设置,就像你一样 User.new(params[:users])