This article uses the installed Rails 6.0.0.
Put together multiple descriptions Make the controller easier to see Use private method use before_action
items_controller.rb
def show
@item = Item.find(params[:id])
end
def edit
@item = Item.find(params[:id])
end
def update
@item = Item.find(params[:id])
end
items_controller.rb
private
def set_item
@item = Item.find(params[:id])
end
First, delete the description of @ (instance variable) in the initial code. And make private at the bottom. Create a method set_item and put the description you deleted earlier in it. (Any method name is fine as long as it is easy to understand) By doing this, you can separate it as a method. However, with this alone, it cannot be called just by cutting it out.
items_controller.rb
before_action :set_item, only: [:show, :edit, :update]
Write this at the top of the controller. To explain one by one before_action: Description to call before each action is executed set_item: Method name created in private of method 1 only: The meaning of the kanji that it is used only for a specific action. The opposite word is expect, which means to use it for something other than a specific action! After that, describe the action name to be specified!
Is it meaningful to make the initial code easier to understand? You may think at first. I was the same. Lol However, it is very convenient because you only need to add the action name to before_action, for example, when you need the same description for another action after this! You can write the code so that it is easy for others to see and not a long description! I will continue to be conscious of applying code that is easier for others to see!
Recommended Posts