0
0

【Rails】ログイン中のユーザーのみ編集・削除できるようにする

Posted at

ログイン中のユーザーのみ編集・削除できるようにするためにensure_correct_userメソッドを作成します。
具体的には、ensure_correct_userメソッドは、リクエストされたリソースの所有者がログイン中のユーザーであることを確認します。もしログイン中のユーザーがリソースの所有者でない場合、権限がないことを通知し、適切なリダイレクトを行います。

以下は、このメソッドの説明と使用例です。

class UsersController < ApplicationController
  before_action :set_user, only: [:edit, :update, :destroy]
  before_action :ensure_correct_user, only: [:edit, :update, :destroy]

  def edit
    # ユーザーの編集ページの表示などの処理
  end

  def update
    if @user.update(user_params)
      redirect_to @user, notice: 'ユーザー情報が更新されました。'
    else
      render :edit
    end
  end

  def destroy
    @user.destroy
    redirect_to users_url, notice: 'ユーザーが削除されました。'
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:name, :email, :password)
  end

  def ensure_correct_user
    if params[:id].to_i != current_user.id
      flash[:notice] = "権限がありません"
      redirect_to posts_index_path
    end
  end
end

この例では、UsersController内でensure_correct_userメソッドが定義され、editupdatedestroyアクションに適用されています。これにより、ログイン中のユーザーが自分のアカウントのみ編集および削除できるようになります。

ensure_correct_userメソッドでは、リクエストされたユーザーのIDとログイン中のユーザーのIDを比較し、一致しない場合は権限がないことを通知して適切なリダイレクトを行います。

0
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
0
0