0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby on Rails】before_actionを使って全てのアクションで同じ処理を行う

Last updated at Posted at 2021-02-28

同じ処理をbefore_actionで定義する。

あるコントローラー内の全てのアクションで1つの処理を使い回したい時。

.rb
class Api::V1::Admin::CompanyAdminsController < ApplicationController

  def index
    company_admins = CompanyAdmin.where(company_id: params[:company_id])
    json_response(200, CompanyAdminIndexSerializer.new(company_admins).to_h)
  end

  def show 
    company_admin = CompanyAdmin.find params[:id]
    json_response(:ok, serialize_data(CompanyAdminIndexSerializer, company_admin))
  end

  def destroy
    company_admin = CompanyAdmin.find params[:id]
    company_admin.destroy!
    json_response(204)
  end
  
end

このコントローラー内を見てみると、show・destroyアクションで同じ処理が書かれている。

company_admin = CompanyAdmin.find params[:id]

これをまとめるために、before_actionと記述する。
これによって、全てのアクションで最初に行いたい処理を実行できる。

  def load_company_admin
    @company_admin = CompanyAdmin.find params[:id]
  end
end

例えば、上のようなメソッドをコントローラー内に記述する。
そして、コントローラー内の一番上にbefore_actionの記述を加える。

最終的なコード

class Api::V1::Admin::CompanyAdminsController < ApplicationController
  before_action :load_company_admin, only: [:show, :destroy] 
  ##onlyオプションを付け加えることで、showとdestroyアクションのときと指定ができる。

  def index
    company_admins = CompanyAdmin.where(company_id: params[:company_id])
    json_response(200, CompanyAdminIndexSerializer.new(company_admins).to_h)
  end

  def show 
    json_response(:ok, serialize_data(CompanyAdminIndexSerializer, @company_admin))
  end

  def destroy
    @company_admin.destroy!
    json_response(204)
  end

  private
  def load_company_admin ##処理の名前を定義する。
    @company_admin = CompanyAdmin.find params[:id]
  end
  ##ここで同じ処理を記述する。
end

少しだけ、このファイルの記述がスッキリした気がする。
何度も同じ記述を書くのはエンジニアとして、あまり優秀ではない気がしているので、できるだけ同じ処理はまとめていきましょう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?