2
2

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.

[Rails6] 共通処理をbefore_actionにまとめる

Posted at

#概要
コントローラのなかで処理を共通化したい場合の方法をしてbefore_actionを使うことを学んだので、
その方法をメモします。

#方法

  • idからDBを一つ取得する処理を共通化する

###privateに共通化する処理を記述

.rb
  private
  def set_question
    @question = Question.find(params[:id])
  end

###before_actionを記述

.rb
class QuestionsController < ApplicationController
  before_action :set_question
end

###実行するアクションを指定したい場合はonlyオプションを追加で記述

.rb
class QuestionsController < ApplicationController
  before_action :set_question, only: [:show, :edit, :destroy, :update]
end

###実行しないアクションを指定する場合はexceptオプションを追加で記述

.rb
class QuestionsController < ApplicationController
  before_action :set_question, except: [:index]
end

#参考文献
【Rails】before_actionの使い方を徹底解説!

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?