備忘録です。
前提
MacOS Catalina
ruby 2.6.5p114
Rails 6.0.3.4
deviseを導入済(authenticate_user!というヘルパーメソッドを使用)
特定ユーザーだけを編集ページへ遷移させる記述
hoges_controller.rb
class HogesController < ApplicationController
before_action :authenticate_user!, only: [:edit]
before_action :specified_hoge, only: [:edit, :update]
before_action :specified_user, only: [:edit]
(中略)
def edit
end
def update
if @hoge.update(hoge_params)
redirect_to root_path
else
render :edit
end
end
private
def hoge_params
params.require(:hoge).permit(:text).merge(fuga_id: params[:fuga_id], user_id: current_user.id)
end
def specified_hoge
@hoge = Hoge.find(params[:id])
end
def specified_user
redirect_to root_path unless @hoge.user.id == current_user.id
end
end
上記のうち、ポイントはココ↓
hoges_controller.rb
before_action :specified_user, only: [:edit]
hoges_controller.rb
def specified_user
redirect_to root_path unless @hoge.user.id == current_user.id
end
before_actionを用いて
1. before_actionの後ろにメソッド名を任意の名前で名付ける。
2. そして、対応するアクション(今回はonlyオプションでeditアクション)を指定する。
3. メソッドに処理を書く。
このようにすることで、例え他のユーザーがURLを手動で書き換え編集ページへ遷移しようとしても、ホーム画面へリダイレクトさせることができる。
今回の場合、hogesテーブルに保存されているユーザーidと現在ログインしているユーザーidが一致しない場合はroot_pathへ遷移させることができます。