LoginSignup
0
1

More than 3 years have passed since last update.

before_actionで同じコードをメソッドにまとめる方法

Posted at

before_actionとは使用すると、コントローラで定義されたアクションが実行される前に、
共通の処理を行うことができるメソッド

修正前

  def show
    @item = Item.find(params[:id])
  end

  def edit
    @item = Item.find(params[:id])
    unless @item.user_id == current_user.id
      redirect_to action: :index
    end
  end

  def update
    @item = Item.find(params[:id])
    if @item.update(item_params)
      redirect_to item_path
    else
      render :edit
    end
  end

showアクション、editアクション、updateアクションに同じ@item = Item.find(params[:id])が
連続して記述してある
また、editアクションにあるunless @item.user_id == current_user.idをアプリの安全性を高めるため、updateアクションでも使えるようにしたい

修正後

  before_action :set_item, only: [:edit, :update, :show]
  before_action :move_to_index, only: [:edit, :update]

  def show
  end

  def edit
  end

  def update
    if @item.update(item_params)
      redirect_to item_path
    else
      render :edit
    end
  end

  private 

  def set_item
    @item = Item.find(params[:id])
  end

  def move_to_index
    unless @item.user_id == current_user.id
      redirect_to action: :index
    end

before_action :set_item, only:[:edit, :update, :show]と記述することでeditアクションと
updateアクションとshowアクションとが実行される前に、set_itemに定義されている処理が実行される
set_itemはプライベートメソッド内に記述
またunless @item.user_id == current_user.idも同じようにbefore_actionで記述して
プライベートメソッド内でmove_to_indexと定義することでeditアクション、updateアクションで使用できる

0
1
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
0
1