Skip to content

Instantly share code, notes, and snippets.

@light-flight
Created October 15, 2025 08:41
Show Gist options
  • Select an option

  • Save light-flight/c73b52003080832d03f631d76f130cf0 to your computer and use it in GitHub Desktop.

Select an option

Save light-flight/c73b52003080832d03f631d76f130cf0 to your computer and use it in GitHub Desktop.
Smart Redirect
class ApplicationController < ActionController::Base
private
# Call this in GET actions like :edit or :new to remember where the user came from.
def store_return_location
referer = request.referer
return unless referer.present? && same_origin?(referer)
flash[:return_to] = referer
end
# Use this after successful POST/PATCH/DELETE to go back, falling back to `fallback`.
def redirect_back_or_to(fallback, status: :see_other, allow_other_host: false)
url = flash.delete(:return_to)
if url.present? && (allow_other_host || same_origin?(url))
redirect_to url, status: status
else
redirect_to fallback, status: status
end
end
# Prevent open redirects by only allowing same-origin URLs.
def same_origin?(url)
uri = URI.parse(url)
uri.host == request.host && uri.scheme == request.scheme && uri.port == request.port
rescue URI::InvalidURIError
false
end
end
class PostsController < ApplicationController
before_action :set_post, only: %i[edit update]
before_action :store_return_location, only: :edit
def edit
# just renders, store_return_location already ran
end
def update
if @post.update(post_params)
redirect_back_or_to @post # returns to index or show depending on where Edit was clicked
else
render :edit, status: :unprocessable_entity
end
end
private
def set_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment