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 5 years have passed since last update.

rails before_actionを行なったあとにアクションを中止する仕組みについて

0
Posted at

はじめに

筆者はrailsチュートリアルを学んでいる時にbeforeアクションの後に他のアクションが実行されない理由について疑問を持ちました。それを自分なりに調べた事を以下にまとめます。
残念ながらbefore_actionの内容は、railsのソースコードを自力で探し出せ読み解けるスキルレベルではないと説明できないため筆者では完璧に理解することはできませんでした。しかしある程度の仕組みを理解できましたので記事にします。

結論

before_ationでredirect_toを行うと、
response_body(コントローラーによって送信されたHTTP応答を返すための変数)が空で無くなるため、before_ationで呼んでいたcallback chainが止まり、以降のbefore_actionやactionが実行されなくなります

使用例

class UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy]

  def index
    @users = User.paginate(page: params[:page])
  end

  # beforeアクション
  # ログイン済みユーザーかどうか
  def logged_in_user
    unless logged_in?
      store_location
      flash[:danger] = "Plaease lon in "
      redirect_to login_url
    end
  end
end

indexを実行する前にlogged_in?redirect_toを実行するとindexは実行されません。

解説

redirect_toなどでresponse_bodyに値が入っている場合は、次のアクションを行わないようです。

詳しい解説は以下の記事を参考にしてください(筆者では完全に説明できるほどのスキルはありません)
Railsでbefore_filter/before_actionがアクションを中止する仕組みを読んでみる

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?