0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

before_actionを使って同じコードをメソッドにまとめよう!

Last updated at Posted at 2021-07-03

コードを記述する際、同じ記述を繰り返ししないといけない時があると思うが
そんな時はbefore_actionとonlyオプションを駆使して可読性を高めよう!

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

  def index
    @items = Item.all.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
  end

  def edit
    unless @item.user == current_user
      redirect_to root_path
    end
  end

  def update
    unless @item.user == current_user
      redirect_to root_path
    end
    if @item.update(item_params)
      redirect_to item_path(@item.id)
    else
      render :edit
    end
  end

  def destroy
    unless @item.user == current_user
      redirect_to root_path
    end
    @item.destroy
    redirect_to root_path
  end


  def item_params
    params.require(:item).permit(:image, :product_name, :product_descriiption, :category_id, :product_condition_id, :price,
                                 :shipping_charge_id, :delivery_area_id, :days_to_delivery_id).merge(user_id: current_user.id)
  end

  private

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

先ず3行目の

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

before_actionを使い処理させたいメソッドを記述。
こちらの場合は:set_itemが処理させたいメソッドに該当する。
次にonlyオプションを使いどのアクションの実行前に処理を実行するのか記述。
ここではshowアクション、editアクション、
updateアクション、destroyアクションで同じ記述を実行させたいということ。

ではその処理させたいメソッドの内容はどこに記述しているのかというと
57行目以降の

 private

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

こちらの記述で呼び出している。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?