[Ruby] 【before_action】

less than 1 minute read

What is ##before_action

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

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

set_action1.png

If the execution contents of the edit action and show action are the same as in the image above, it is better to put them together as a common process so that readability is improved and it is convenient when making changes, so put together the processes.

set_action2.png

First, delete the corresponding action.

set_action3.png

After that, the common processing contents deleted earlier are defined as set_action in the private method part.

set_action5.png

Finally, describe 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 describing only as an option, set_action should be executed only for the corresponding action.