在使用 Rails 4.x 中的 has_secure_password 功能时获取密码不能为空:
这是我的文件:
Gemfile 有并且我做了捆绑安装:
gem '密码'
这是表格
create_table :teachers do |t|
t.string :firstname, null: false
t.string :lastname, null: false
t.string :email, null: false
t.string :cellphone
t.string :username, null: false
t.string :password_digest, null: false
t.string :addr_streetno
t.integer :addr_aptno
t.string :addr_city
t.string :addr_state
t.integer :addr_zip
t.binary :photo, :limit => 0.5.megabyte
t.timestamps
end
这是模型文件:
class Teacher < ActiveRecord::Base
has_many :students
has_secure_password
attr_accessor :password, :password_confirmation
validates_presence_of :password, :on => :create
EMAIL_REGEX = /\A[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
end
这是表单中密码字段的代码:
<tr>
<th>Password</th>
<td><%= f.password_field :password %></td>
</tr>
<tr>
<th>Confirm Password</th>
<td><%= f.password_field :password_confirmation %></td>
</tr>
<tr>
这是 Controller 代码:
class TeacherController < ApplicationController
def index
@teachers= Teacher.all
end
def new
@teacher = Teacher.new
end
def create
@teacher = Teacher.new(teacher_params)
if @teacher.save
redirect_to :action => 'index'
else
render :action => 'new'
end
end
def edit
end
def show
end
private
def teacher_params
params.require(:teacher).permit(:firstname,
:lastname,
:dob,
:email,
:cellphone,
:username,
:password,
:password_confirmation,
:addr_streetno,
:addr_aptno,
:addr_city,
:addr_state,
:addr_zip,
:photo)
end
end
最佳答案
attr_accessor :password, :password_confirmation
在 Teacher 类中注释这一行。
关于ruby-on-rails - 使用 has_secure_password 获取密码不能为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23723319/