[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.


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.


First, delete the corresponding action.


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


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.