LoginSignup
1
0

More than 3 years have passed since last update.

【Ruby On Rails】特定のユーザーだけが編集ページに遷移できるようにする記述

Last updated at Posted at 2020-12-28

備忘録です。

前提

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へ遷移させることができます。

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