What is before_action

before_action is a method that can perform common processing before executing the processing defined in the controller.

This time, I will write an example of using before_action when the execution contents of the method in the controller are duplicated.


If the execution contents of the edit action and the show action are the same as in the image above, it is better to combine them as a common process for better readability and it is convenient when changing, so the processes are summarized.


First delete the corresponding action.


After that, define the common processing content deleted earlier as set_action in the private method part.


Finally, write before_action at the top of the controller. In this case, we want to apply set_action only to edit and show actions, so by writing only as an option, set_action should be executed only for the corresponding action.

Recommended Posts

Use before_action! !!
What is before_action?