How to redirect users to a custom web page each time `params` contain a `redirect_uri` value?

穿精又带淫゛_ 提交于 2019-12-24 15:07:07

问题


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


来源:https://stackoverflow.com/questions/27763607/how-to-redirect-users-to-a-custom-web-page-each-time-params-contain-a-redirec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!