How to redirect users to a custom web page each ti

2019-08-06 10:11发布

问题:

I am running Ruby on Rails 4.1 and I would like to implement a feature that redirects users to a custom web page when they perform an action by providing a redirect_uri parameter. In other words, I would like to "trigger" the redirection each time the redirect_uri value is present in params and the redirection should happen in any case (e.g., when GET, POST, PUT and DELETE HTTP requests are executed with HTML or JS formats) after the process flow has been fully accomplished (e.g., when the HTTP verb is POST then the redirection should happen after submission).

Bonus - If possible, I would like to validate the URL (e.g., link correctness) in cases when the referrer URL comes from outside the application domain.

How should I make that the proper way?

回答1:

From this discussion, once your action encounters redirect_to/render statements, the request flow will be complete and after_action redirect may not be trigerred.

How about creating a controller action like custom_redirect_to as:

class ApplicationController < ActionController::Base
  def custom_redirect_to(url)
    redirect_to (params[:redirect_uri].present? ? params[:redirect_uri] : url)
  end
end

and then use this method in your controller actions instead of redirect_to as:

def create
  @post = Post.new(params)
  if @post.save
    custom_redirect_to @post
  else
    render 'new'
  end
end