2016-08-13 222 views
-1

我正在尝试为更改用户密码创建一个单独的视图,我不知道该怎么做。当我开始时,我意识到它需要不同的方法,并且可能会在模型中进行一些验证。 我需要帮助,我该如何做到这一点。我不知道,我需要包含在控制器,模型和视图中。 我也在执行“输入旧密码来创建新密码”。Ruby on Rails身份验证

+0

您是否在使用Devise?还是你推出了自己的认证系统? –

+0

我已经通过自己的认证系统实施。 –

回答

0

我建议你遵循RESTful原则。

在您的项目中使用editupdate动作创建PasswordsController

然后用密码更改的表单创建edit.html.erb视图。

模型中的验证取决于您的要求。

以下是这上面的例子:

控制器:

class PasswordsController < ApplicationController 
    before_action :set_user 
    before_action :check_current_password, only: :update 

    def edit 
    end 

    def update 
    if @user.update password_params 
     flash[:success] = 'Password changed' 
     redirect_to user_path # Your user's profile for example 
    else 
     flash[:danger] = 'Error' 
     render :edit 
    end 
    end 

    private 

    def password_params 
    params.require(:user).permit(:password, :password_confirmation) 
    end 

    def set_user 
    @user = current_user # Your current user 
    end 

    def check_current_password 
    unless @user.authenticate(params[:current_password]) 
     raise # I would recommend you to work with exceptions here because you interrupt the process. 
      # You can make it also a bit more specific if you define an exception class and just catch them. 
    end 
    rescue 
    flash[:danger] = 'Current password incorrect!' 
    redirect_to password_path(current_user) # Redirect back to the change page 
    end 
end 

查看:

<!-- HTML skeleton is in application.html.erb --> 

<%= form_for @user, url: password_path, method: :patch do |f| %> 
    <%= text_field_tag :current_password %> 

    <%= f.text_field :password %> 
    <%= f.text_field :password_confirmation %> 

    <%= f.submit 'Change password' %> 
<% end %> 

假设你已经安装了bcrypt宝石和用户模式有一个字段password_digest,你的模型应该是这样的。

型号:

class User < ApplicationRecord 
    has_secure_password 
end 

这是一个非常简单的实现密码更改的。我没有测试过它,但它只是在这里给你一个想法是如何工作的。

欲了解更多信息,请参阅https://gist.github.com/thebucknerlife/10090014#steps

+0

谢谢。但问题是用户必须输入当前密码才能创建新密码。 –

+0

然后添加另一个需要当前密码的字段,并在更新之前在控制器中检查它。我会更新我的答案。 – Tobias

相关问题