未ログインユーザーの転送

⭐️タスク

現在、ログインしているユーザーが別のユーザーの編集ページのURLを記入すると編集ページに飛べてしまう😓

トップページに飛ばしたい!

⭐️答えの手前

def edit
@item = Item.find(params[:id])
unless @item.user_id == current_user.id
redirect_to root_path
#editさせない処理
end

 

⭐️答え

class ItemsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_item, only: [:show, :edit, :update]
before_action :root_item, only:[:edit, :update]
 

〜省略〜
 
def edit
end
 
def update
if @item.update(item_params)
redirect_to item_path(@item)
else
render :edit
end 
end
private
 
~省略〜 
 
def root_item
unless @item.user_id == current_user.id
redirect_to root_path
end
end

end

  

⭐️チェックポイント

1、編集ページを管轄しているのは、editのコントローラー

2、unless を使って条件分岐 unlessはfalshの時に処理が実行される(if文と逆)

3、#editさせない処理()

4、2、3をupdateアクションにも適用させる

 

⭐️解説

1、編集ページに飛ばせたくないので、編集を管理しているeditコントローラーにその旨を伝える。

 

2、unlessを使う

その商品のユーザーと今操作しているユーザーが一緒じゃない時

unless @item.user_id == current_user.id

トップページに飛ばしてください!

redirect_to root_path

 

3、updateアクションにも適用させたい!

理由→検証ツールなどを用いてリクエストを改ざんすることで、編集画面を経由せずにupdateアクションを動かすことが可能です。  
そういった行為への対策として、updateアクションにもeditアクションと同様の条件分岐を加えることが必要となります。

 

4、新しくメソッドを定義して、before_actionで呼び出す!

 

以上でできました!😁