gpt4 book ai didi

ruby-on-rails - 需要旧密码才能创建新密码

转载 作者:行者123 更新时间:2023-12-04 03:34:30 24 4
gpt4 key购买 nike

现在,每次我在用户/编辑中进行任何更改时,表单都要求用户设置一个新密码。我希望它仅在输入新密码的情况下才要求输入当前密码(如何要求输入当前密码?)。我要如何实现这一点,非常感谢。

<%= 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和Web上的一些信息,我提出了以下解决方案。

用户/编辑 View :

<%= 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? }

用户 Controller :
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

关于ruby-on-rails - 需要旧密码才能创建新密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15805190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com