[RUBY] [Before_action]

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.

set_action1.png

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.

set_action2.png

First delete the corresponding action.

set_action3.png

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

set_action5.png

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

[Before_action]
Use before_action! !!
What is before_action?