Together网站搭建之踩坑系列8

这是功能实现的第七篇,扯一扯如何在个人中心实作密码修改.

完整作品源码及效果,看这里作品网站, 作品源码

目录

正文

这里修改用户名和头像简单带过,我们专注于密码修改

来动动我们熟悉的devise。

先看效果,在个人中心添加密码修改板块:

具体步骤:

  • 终端运行:rails g controller account::users

  • app/controllers/account/users_controller.eb中,仅有头像和用户名的update:

    class Account::UsersController < ApplicationController
      before_action :authenticate_user!
    
      def index
        @user = current_user
      end
    
      def show
        @user = current_user
      end
    
      def edit
        @user = current_user
      end
    
      def update
        @user = current_user
        if @user.update(user_params)
          redirect_to account_user_path, notice: "信息更新成功"
        else
          render :edit
        end
      end
    
      private
    
      def user_params
        params.require(:user).permit(:username, :avatar)
      end
    end
    
  • app/views/account/users/show.html.erb中,添加密码修改部分:

    ........
    <%= simple_form_for [:account, @user] do |f| %>
     ......
      <div class="my_password">
        <h4>修改密码: </h4>
        <%= f.input :current_password, label: "旧密码:", hint: false, error_html: { id: 'password_error'} %>
        <%= f.input :password, label: "新密码:", hint: false, error_html: { id: 'password_error'} %>
        <%= f.input :password_confirmation, label: "密码确认:"%>
      </div>
      <br>
      .......
      <div class="form-group">
        <%= f.submit "更新", class: "btn btn-success"%>
      </div>
    <% end %>
    .......
    
  • app/controllers/account/users_controller.eb中,做如下修改:

      ......
      def update
        @user = current_user
      - if @user.update(user_params)
      -   redirect_to account_user_path, notice: "信息更新成功"
      +  if @user.update_with_password(user_params)
      +     bypass_sign_in(@user)
      +     redirect_to account_user_path, notice: "密码更新成功"
      +  elsif @user.update(user_params)
      +     redirect_to account_user_path, notice: "信息更新成功"
        else
            render :edit
        end
      end
    
      private
    
      def user_params
      -    params.require(:user).permit(:username, :avatar)
      + params.require(:user).permit(:username, :avatar, :password, :password_confirmation)
      end
    

这样就OK啦,可以在个人中心页面修改密码,保存后退出,重新登陆,会发现密码已经修改了。

参考:

how to allow user to edit their password