[RUBY] I separated the same description as a method under private in Rails controller and implemented it so that it can be called by before_action

This article uses the installed Rails 6.0.0.

things to do

Put together multiple descriptions Make the controller easier to see Use private method use before_action

Initial code

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 
As you can see, similar descriptions are used in multiple actions. I would like to separate this and call it! ]

Method 1 ~ I will divide it into private and below ~

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.

Method 2 ~ I'll call it with before_action ~

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!

Finally

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

I separated the same description as a method under private in Rails controller and implemented it so that it can be called by before_action
I implemented the multiple image upload function in Rails so that multiple images can be slid for the post
I tried a puzzle that can only be solved by the bottom 10% of bad engineers
An active hash that can be treated as data even if it is not in the database
How to test a private method in Java and partially mock that method
[Rails] "pry-rails" that can be used when saving with the create method
Continuation ・ Active hash that can be handled as data even if it is not in the database ~ Display
Delegated type added in Rails 6.1 and Union types of GraphQL seem to be compatible, so I tried it