LoginSignup
0
1

More than 1 year has passed since last update.

コールバック処理を実現する(before_action)

Posted at

コントローラーのアクションを記述する際に、全く同じ文を記述していることはないでしょうか?例えば下の記述のような感じです。

#Drink Controller

def edit
  @drink = Drink.find(params[:id])
end

def destroy
  @drink = Drink.find(params[:id])
  @drink.destroy
  ~~省略~~
end

このような感じでeditとdestroyの一行目が同じ処理を記述していますよね。
こう言う時はbefore_actionでまとめてあげましょう。


before_action: set_drink, only: [:edit, :destroy]

def edit; end

def destroy
  @drink.destroy
  ~~省略~~
end

def set_drink
  @drink = Drink.find(params[:id])
end

このような感じでコードをすっきり書くことができます。
同じ処理は何度もかくより一つにまとめて書く習慣をつけていきます。

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