我跟随这个视频教程,学习如何从头开始创建身份验证:
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
中的值保存到User表中的密码字段,但该字段在数据库中不存在。在视频中,他提到要修复这个bug,我应该只添加:attr_accessible :password
到我的模型,它应该工作,但我得到以下错误:
UsersController#create中的NoMethodError
为#
定义方法' password'app/controllers/users_controller。rb: 8:在"创建"
有什么建议吗?我只是想利用使用强类型模型而不是松散的html字段带来的验证。
您有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
attr_accessor
创建的虚拟属性不能作为数据库字段使用(因此是虚拟的)。
attr_accessible
是一种安全机制,允许通过批量分配设置白名单属性,就像User.new(params[:users])