需要旧密码才能创建新密码 [英] Require old password to make new password
本文介绍了需要旧密码才能创建新密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在,每当我在用户/编辑中进行任何更改时,表单都要求用户设置新密码.我希望它仅在输入新密码的情况下才要求输入当前密码(如何要求输入当前密码?).我要如何实现这一点,非常感谢.
Right now every time I change anything in user/edit the form requires the user to set a new password. I would like for it to require the current password (how can I ask for current password?) only incase a new password is entered. How can I achieve this, thanks a lot for this.
<%= form_for(@user, :html => {:multipart => true}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name, placeholder: :name %>
<%= f.text_field :email, placeholder: :email %>
<%= f.password_field :password, placeholder: "Enter new password" %>
<%= f.password_field :password_confirmation, placeholder: "Confirm new password" %>
<%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
<% end %>
推荐答案
使用rails_has_elegance和网络上的一些信息,我提出了以下解决方案.
Using some info from rails_has_elegance and the web I came up with the following solution.
用户/编辑视图:
<%= form_for(@user, :html => {:multipart => true}) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name, placeholder: :name %>
<%= f.text_field :email, placeholder: :email %>
<%= password_field_tag :current_password, params[:current_password], placeholder: "Current password" %>
<%= f.password_field :password, placeholder: "New password (optional)" %>
<%= f.password_field :password_confirmation, placeholder: "Confirm new password" %>
<% end %>
用户模型:
validates :password, :on => :create
validates :password_confirmation, presence: true, :on => :update, :unless => lambda{ |user| user.password.blank? }
用户控制器:
def update
@user = User.find(params[:id])
user = User.find_by_email(current_user.email).try(:authenticate, params[:current_password])
if user && @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
flash.now[:error] = "Incorrect Current Password" unless user
sign_in @user
render 'edit'
end
end
这篇关于需要旧密码才能创建新密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文