before_actionの使い方とコードの可読性の上げ方

コントローラーのアクションで下記のような選んだ商品と現在ログイン中のユーザーが同じか確認する記述がありました。何度も同じ記述を繰り返さないためにどうすればいいか記録していきます。

 

 

app/controllers/items_controller.rb
def edit
 @item = current_user.items.find_by(id: params[:id])
 unless @item
 redirect_to root_path
 end
end
 
def update
 @item = current_user.items.find_by(id: params[:id])
 unless @item
  redirect_to root_path
 end
 if @item.update(item_params)
  redirect_to item_path
 else
  render :edit
 end
end

 

上記の場合、コントローラーのアクションで下記のような選んだ商品と現在ログイン中のユーザーが同じか確認する記述がeditアクションとupdateアクションで出てきます。

 

app/controllers/items_controller.rb
@item = current_user.items.find_by(id: params[:id])
unless @item
redirect_to root_path
end

 

コードを簡潔にするためbefore_actionで上記コードをまとめると可読性が上がります。

before_actionは指定したアクションの前に自動で実行する処理を書いておくものです。

before_action+使いまわしたいメソッド名+アクション名で記述します。

 

before_action :correct_user, only: [:edit, :update]
def edit
 
end

def update
 if @item.update(item_params)
  redirect_to item_path
 else
  render :edit
 end
end
private
def correct_user
 @item = current_user.items.find_by(id: params[:id])
 unless @item
  redirect_to root_path
 end
end

 

まとめたい処理をcurrent_userとメソッド化することでbefore_actionで使えるようになります。

 

まとめ

before_actionでコードをまとめることで可読性が上がり、修正時も一部分を修正するだけでよいので、できるだけまとめるように心がけたいですね。