2
3

More than 3 years have passed since last update.

【Ruby】before_actionとは何か?引数を渡す方法とオプションの使い方実例。

Posted at

【Ruby】before_actionとは何か?引数を渡す方法とオプションの使い方実例。

before_actionとは何か?

各アクションが動く前に実行する処理を記述できる。
コントローラの冒頭に記述する。

記述方法

  1. 引数なしの場合
  2. 引数ありの場合
  3. オプション

1. 引数なしの場合

before_action :<メソッド名>

メソッドは同じファイルの下部に記述する。(※引数を渡すとエラーになる)



▼実例

before_actionの例
class UsersController < ApplicationController

  before_action :require_permission

  #(省略)アクションを記述

  #before_actionの処理
  def require_permission
    unless current_user.partner? || current_user.admin?
      redirect_to admin_root_path, alert: 'ここから先は管理者限定です!'
    end
end

アクションを実行する前に、require_permissionを実行する。
もし、current_userのpartnerかadminの値が存在しなければ、admin_root_pathにリダイレクトする。その際にalartを表示する。

unless文

条件式がfalseなら処理を実行する。
if !条件式と同じ

unless 条件式 
  処理
end

||

または(or)。

オブジェクトcurrent_userのpartnerまたはadminの値が存在すればtrue, 存在しなければfalseを返す。

redirect_to

redirect_to <リダイレクト先>[, <オプション名>: <値>]

alert:で、アラートを表示する

(参考)Ruby公式 redirect_to


2. 引数ありの場合

処理に引数を渡す場合は、矢印と波かっこ→ { }を使う。

before_action ->{ 処理 }

  • 引数を渡さない場合でも使える。

▼実例

before_actionの例
class UsersController < ApplicationController

  before_action ->{
    require_permission("password")
  }

  #(省略)アクションを記述

  #before_actionの処理
  def require_permission("password")
    unless password === "xxxxx"
      redirect_to admin_root_path, alert: 'ここから先は管理者限定です!'
    end
end


処理を複数記述する

処理を複数記述する場合も、->{ }を使う。

  before_action ->{ 処理1, 処理2 }


3. オプション

オプションをつけることで条件を絞ることができる。

オプション 内容
:only 実行するアクション
:except 実行しないアクション
:if 実行する条件
:unless 実行しない条件

例えば、createとshowアクションのみに適用したい場合は、only: [:create, :show]をつける。

before_actionの例
class UsersController < ApplicationController

  before_action :require_permission, only: [:create, :show]

  #(一部省略)アクションを記述
    create: {
      create_params: :users_params,
      json_renderer: :show_renderer,
    },
    show: {
      json_renderer: :show_renderer,
    },

  #before_actionの処理
  def require_permission
    unless current_user.partner? || current_user.admin?
      redirect_to admin_root_path, alert: 'ここから先は管理者限定です!'
    end
end



->{ }を使った場合も同じ

before_actionの例
class UsersController < ApplicationController

  before_action ->{require_permission}, only: [:create, :show]

  #(一部省略)アクションを記述
    create: {
      create_params: :users_params,
      json_renderer: :show_renderer,
    },
    show: {
      json_renderer: :show_renderer,
    },

  #before_actionの処理
  def require_permission
    unless current_user.partner? || current_user.admin?
      redirect_to admin_root_path, alert: 'ここから先は管理者限定です!'
    end
end



Rails公式 before_action

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