Controller redirect to different paths depending on previous page

对着背影说爱祢 提交于 2019-12-10 21:55:23

问题


Question:

How I want to redirect to different path after create action, given if previous_page is ../reader/new goes to ../reader/blog/:id, whereas if previous_page is ../editor/new goes to ../editor/blog/:id.

Explaination:

I want to modify the controller actions so that it can redirect to different path depending on which page it comes from. For example, I have a reader, editor and blog model. Both reader and editor can create a blog.

Here is the original blogs_controller:

    class BlogsController < ApplicationsController        
      def create
        @blog = Blog.new(blog_params)
        respond_to do |format|
          if @blog.save
            format.html { redirect_to @blog }
          else
            format.html { render :new }
          end
        end
      end

      private

      def blog_params
        params.require(:service).permit(:title, :content)
      end
    end

回答1:


You have a few options:

  • use redirect_to :back in the controller if all you need is redirecting back to the previous page
  • add some logic processing the HTTP referer, i.e. decide where to redirect based on request.referer in the controller
  • pass the redirection info in a parameter to the create action, e.g. pass params[:redirect_to] = "reader" when coming from the "reader" page and decide where to redirect based on this parameter. You can even place the whole URI to redirect into the param and just redirect to it (but this approach is unsafe as params can be mangled by users).

Generally, I'd choose the third option (parameters) as you have the best control over the redirection process (the first two options rely on HTTP referer which can also be mangled by any visitor, thus are potentially unsafe).



来源:https://stackoverflow.com/questions/35897322/controller-redirect-to-different-paths-depending-on-previous-page

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