LoginSignup
160
118

More than 3 years have passed since last update.

Rails 5.1系からは redirect_to :backがきえまっせ

Last updated at Posted at 2016-12-04

redirect_to :backをなんとなく使ってみたら

DEPRECATION WARNING: redirect_to :back is deprecated and will be removed from Rails 5.1. Please use redirect_back(fallback_location: fallback_location) where fallback_location represents the location to use if the request has no HTTP referer information.

..とおこられてしまった.
つまり
request.refererがnilなとき,fallback_locationにリダイレクトしてくれる

ってことなんでしょうが、なんでそもそもredirect_to :backが非推奨なのか少し調べてみました.

HTTP_REFERERがないときActionController::RedirectBackErrorが発生

class PostsController < ApplicationController
  def publish
    post = Post.find params[:id]
    post.publish!

    redirect_to :back
  end
end

こういう実装にしたとき,HTTP_REFERERがないことでエラーになってしまうことを防ぐため
これまでは

class PostsController < ApplicationController
  rescue_from ActionController::RedirectBackError, with: :redirect_to_default

  def publish
    post = Post.find params[:id]
    post.publish!
    redirect_to :back
  end

  private

  def redirect_to_default
    redirect_to root_path
  end
end

としていたと.

Rails 5.1系からは

redirect_to :back

redirect_back(fallback_location: root_path)におきかわりrescueしなくてもよいみたいです

class PostsController < ApplicationController
  def publish
    post = Post.find params[:id]
    post.publish!

    redirect_back(fallback_location: root_path)
  end
end

としておけばエラーが出る前にroot_pathにとんでくれるようになりました.

160
118
1

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
160
118