きっかけ
viewファイルに条件分岐を作っていても、そもそもUrlから直打ちされてしまうとページに飛ばれてしまうことに気づいたため。
結論
任意のコントローラーにbefore_actionを使って、アクションを起こす前段階の条件分岐を作っておく。
コード
items.controller.rb
class ItemsController < ApplicationController
#before_actionを使って、コントーラーのアクションに飛ぶ前に条件分岐をかける
before_action :correct_user, only: [:edit]
before_action :item_find, only: [:show, :edit, :update, :destroy]
def edit
end
private
def item_params
params.require(:item).permit(:title, :explain, :category_id, :condition_id, :price, :delivery_fee_id, :prefecture_id, :delivery_date_id, :image).merge(user_id: current_user.id)
end
# before_actionをかけたメソッドでユーザーの選別を行っている
def correct_user
@item = Item.find(params[:id])
if user_signed_in? && @item.user == current_user
render :edit
else
redirect_to root_path
end
end
補足
Urlに直打ちしているということは、ルーティングを経由して必ずコントローラーにページの開示を求めにくるから、コントーラーに記述する必要がある。MVCの流れを今一度再確認できた。