加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 22:43:22 所属栏目:百科 来源:网络整理
导读:现在,每当我在用户/编辑中更改任何内容时,表单都要求用户设置新密码.我想要它需要当前密码(我怎么能要求当前密码?)只是输入了一个新密码.我怎么能实现这一点,非常感谢. %= form_for(@user,:html = {:multipart = true}) do |f| % %= render 'shared/error_m
现在,每当我在用户/编辑中更改任何内容时,表单都要求用户设置新密码.我想要它需要当前密码(我怎么能要求当前密码?)只是输入了一个新密码.我怎么能实现这一点,非常感谢.
<%= 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中的一些信息,我想出了以下解决方案.

用户/编辑视图:

<%= form_for(@user,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读