LoginSignup
1
0

マイページを編集するときにパスワードなしで編集可能にする

Last updated at Posted at 2023-07-23

はじめに

初めまして、プログラミングスクールGeekSalonのWebコースメンターをしています。 

今回の記事は、ユーザーマイページ(プロフィールページ)を編集する際にパスワードを入力せずに編集を可能にする方法をお教えします。 

前提 

・Railsバージョン: 5.0以上
・Deviseバージョン: 4.2以上
・ログインページが実装されている
・ユーザーマイページ(プロフィールページ)が実装されていること 

Deviseでは、アカウントをアップデートする際に、3つのパスワード情報が必要になります。

password
password_confirmation
current_password

パスワードを3回も打つ理由としては、パスワードの誤入力を防止、不正なアクセスを防止などが挙げられます。ただ、プロフィールを編集するために、パスワードを3つも入力させるのは、マジで面倒です。 

なので、パスワードなしで実装する方法をこの記事のゴールとします。

1.RegistrationsControllerの作成

rails g controller registrations

ターミナルに上記のコードを打つちみます。

作成したら、以下のコードを追加してください。 

app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  #ここから
  def update_resource(resource, params)
    # パスワード変更を行う場合のみ、current_passwordも含めて更新する
    if params[:password].present? && params[:password_confirmation].present?
      resource.update_with_password(params)
    else
      # パスワード変更を行わない場合は、通常の更新を行う
      resource.update_without_password(params.except(:current_password))
    end
  end
  #ここまで
end

これにより、パスワード変更が必要な場合にはcurrent_passwordも含めて更新が行われ、パスワード変更を行わない場合にはcurrent_passwordを除外して更新が行われるようになります。 

routes.rbに指定 

config/routes.rb 
Rails.application.routes.draw do
  devise_for :users, # この行にカンマを追加
    controllers: { registrations: 'registrations' } # この行を追加

  resources :users, only: [:show]
end

modelのコードを追加 

app/models/user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  
  validates :name, presence: true
  validates :self_introduction, length: { maximum: 500 }


  # ==========ここから追加する==========
  def update_without_current_password(params, *options)

    if params[:password].blank? && params[:password_confirmation].blank?
      params.delete(:password)
      params.delete(:password_confirmation)
    end

    result = update_attributes(params, *options)
    clean_up_passwords
    result
  end
  # ==========ここまで追加する==========

end
app/models/user.rb 
params.delete(:password)
params.delete(:password_confirmation)

上記のコードでpasswordとpassword_confirmationのパラメータを削除しています。

app/models/user.rb 
if params[:password].blank? && params[:password_confirmation].blank?

このコードで、パスワードとパスワードの確認のフォームが空のときにtrueを返すif式です。

blank?は中身が空か、入れものそのものが存在しないときにtrueを返すRubyのメソッドです。 

「保存」ボタンを押したあと、トップページに遷移すればうまく動作しています。

以上で本パートは終了です。

お疲れさまでした。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0