コントローラー内の記述でかぶっているものについてまとめてくれる、そんな素晴らしいコマンド「before_action」編です。
class ItemsController < ApplicationController
def index
@items = Item.order('created_at DESC')
end
def new
@item = Item.new
end
def create
@item = Item.new(item_params)
if @item.save
redirect_to root_path
else
render :new
end
end
def show
@item = Item.find(params[:id])
end
def edit
@item = Item.find(params[:id])
redirect_to root_path unless current_user.id == @item.user_id
end
def update
@item = Item.find(params[:id])
@item.update(item_params)
if @item.save
redirect_to root_path
else
render :edit
end
end
end
アクション内でかぶっている記述がありますね。
上から順番に
show
edit
update
以上3つの「@item = Item.new(item_params)」という記述です。
これをbefore_actionを使ってまとめてみます。
class ItemsController < ApplicationController
before_action :find_item ⬅️❶まずこれを記述して
〜略〜
def show
@item = Item.find(params[:id]) ⬅️❷これを消してく
end
def edit
@item = Item.find(params[:id]) ⬅️❷これを消してく
redirect_to root_path unless current_user.id == @item.user_id
end
def update
@item = Item.find(params[:id]) ⬅️❷これを消してく
@item.update(item_params)
if @item.save
redirect_to root_path
else
render :edit
end
end
private ⬅️❸privateメソッドにして
def find_item ⬅️❹find_itemという名前のメソッドを定義して、中身はかぶっている記述をIN
@item = Item.find(params[:id])
end
そしてページ更新!
はい!エラーになりました!笑
定義したfind_itemメソッドは、かぶっていて記述を削ったアクションにだけ必要になっている。
つまりshow、edit、updateの3つにだけ適用したい。
そんな時はonlyアクションでしたね。しぼっちゃいましょう。
class ItemsController < ApplicationController
before_action :find_item, only: [:show, :edit, :update] ⬅️❶ここに追加
〜略〜
def show
end
def edit
redirect_to root_path unless current_user.id == @item.user_id
end
def update
@item.update(item_params)
if @item.save
redirect_to root_path
else
render :edit
end
end
private
def find_ite
@item = Item.find(params[:id])
end
だいぶスッキリしました。
ずっと同じファイルで記述しているとこういうことが起きやすいのかなと思いました。
コードが増えてきたら一度整理&確認してみることが大事ですね。
今日も良い経験になりました。