【发布时间】: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