[Specific usage of before_action] Rails refactoring

What is before_action?

before_action is a type of refactoring that you can use with your Rails controller.

** If you use before_action Common actions can be taken before the actions defined in the controller are performed. ** **

Specific usage

Let's take a look at the controller inside as follows.

app/controllers/tweets_controller.rb


class TweetsController < ApplicationController

  def index
    @tweets = Tweet.all
  end

  def new
    @tweet = Tweet.new
  end


  def create
    Tweet.create(tweet_params)
  end

  def destroy
    tweet = Tweet.find(params[:id])
    tweet.destroy
  end

  def edit
    @tweet = Tweet.find(params[:id])
  end

  def update
    tweet = Tweet.find(params[:id])
    tweet.update(tweet_params)
  end

  def show
    @tweet = Tweet.find(params[:id])
  end
  
  private
  def tweet_params
    params.require(:tweet).permit(:distance, :image)
  end
end

If you look closely, of the seven actions of Rails, The contents of the edit and show actions are @tweet = Tweet.find(params[:id]) Is used repeatedly.

To ** refactor and improve readability of such code **, Use before_action as follows:

app/controllers/tweets_controller.rb


class TweetsController < ApplicationController
  before_action :set_tweet, only: [:edit, :show]

  def index
    @tweets = Tweet.all
  end

  def new
    @tweet = Tweet.new
  end

  def create
    Tweet.create(tweet_params)
  end

  def destroy
    tweet = Tweet.find(params[:id])
    tweet.destroy
  end

  def edit
  end

  def update
    tweet = Tweet.find(params[:id])
    tweet.update(tweet_params)
  end

  def show
  end

  private

  def tweet_params
    params.require(:tweet).permit(:name, :image, :text)
  end

  def set_tweet
    @tweet = Tweet.find(params[:id])
  end
end

in this way, Using before_action, it is executed before two actions, edit and show, Define a new method called set_tweet (method name is decided by yourself)

I used it repeatedly earlier @tweet = Tweet.find(params[:id]) It becomes possible to put together.

Summary

By using before_action You can prevent the code from becoming redundant and improve the readability of the code!

The code given as an example this time is The contents of the two actions edit and show were the same, The more code you use repeatedly, the bigger the effect!

As a Rails refactoring Please try to reference!

Recommended Posts

[Specific usage of before_action] Rails refactoring
[Rails] Differences and usage of each_with_index and each.with_index
[Rails] Introduction of PAY.JP
Minimal usage of Mockito
Rails Tutorial/Significance of Indexing
Rails implementation of ajax removal
[Rails] Introduction of devise Basics
[Java] Mirage-Basic usage of SQL
[Rails 6] Implementation of search function
[Rails] Implementation of category function
Super basic usage of Eclipse
[Rails] Implementation of tutorial function