0
1

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 2020-07-14

before_actionとは

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

今回はコントローラー内のメソッドの実行内容が重複している場合のbefore_actionの使用例を書いていきます。

set_action1.png

上の画像のようにeditアクションとshowアクションの実行内容が同じである場合は共通の処理としてまとめてしまった方が可読性も上がり、変更の際も便利なので処理をまとめる。

set_action2.png

まず該当のアクションを削除。

set_action3.png

その後先ほど削除した共通していた処理内容をprivateメソッドの部分にset_actionとして定義する。

set_action5.png

最後にコントローラーの上部にbefore_actionを記述する。
今回の場合はset_actionを適用させたいのはeditとshowアクションのみなのでオプションとしてonlyを記述することで該当のアクションにのみset_actionを実行させれば良い。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?