2016-08-13 12 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