我有一个使用 Rails 构建的用户has_secure_password
模型(基于Rails 教程书):
架构.rb:
create_table "users", :force => true do |t|
t.string "password_digest"
end
用户.rb:
class User < ActiveRecord::Base
attr_accessible :name, :email, :avatar, :password, :password_confirmation, :provider, :uid
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
我有这样的看法uses/password_edit.html.erb
:
<%= f.label :password %>
<%= f.password_field :password, "New Password" %>
<%= f.label :password_confirmation, "Retype Password" %>
<%= f.password_field :password_confirmation %>
现在,我想:current_password
在顶部添加一个字段。问题是数据库只有一password_digest
列。
所以,我在这里有点迷路了。我什至不确定如何使表单在不正确时引发current_password
错误。
有什么建议么?
编辑:
users_controller.html.erb:
def update old_password = params[:current_password]
if authenticated = User.authenticate(old_password)
if params[:user][:password].blank? && params[:user][:password_confirmation].blank?
# Use old password if none indicated
params[:user][:password] = old_password
params[:user][:password_confirmation] = old_password
end
end
@user = User.find(params[:id])
@user.errors.add(:base, "Invalid password") unless authenticated
@user.updating_password = true if params[:form_name] == "edit_password"
if authenticated && @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
if params[:form_name] == "edit_password"
render 'edit_password'
else
render 'edit'
end
end
@user.updating_password = nil
结尾