ログイン中のユーザーのみ編集・削除できるようにするために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
メソッドが定義され、edit
、update
、destroy
アクションに適用されています。これにより、ログイン中のユーザーが自分のアカウントのみ編集および削除できるようになります。
ensure_correct_user
メソッドでは、リクエストされたユーザーのIDとログイン中のユーザーのIDを比較し、一致しない場合は権限がないことを通知して適切なリダイレクトを行います。