控制器重定向到不同的路径,具体取决于上一页 [英] Controller redirect to different paths depending on previous page

查看:88
本文介绍了控制器重定向到不同的路径,具体取决于上一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

create 操作之后,如果previous_page是 ../ reader / new 转到 ../ reader / blog /:id ,而如果previous_page是 ../ editor / new 转到 ../ editor / blog /:id

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.

说明:

我想修改控制器操作,以便它可以重定向到不同的路径,具体取决于它来自哪个页面。例如,我有一个阅读器编辑器博客模型。 阅读器编辑器都可以创建博客

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.

以下是原始的 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


推荐答案

您有几种选择:


  • 在控制器中使用 redirect_to:back 如果您需要的全部是将重定向到前一页

  • 添加一些处理 HTTP引用的逻辑,即根据 request.referer 在控制器中

  • 将参数中的重定向信息传递给 create 行动,例如当来自阅读器页面时,通过 params [:redirect_to] =阅读器 并根据此参数决定重定向的位置。您甚至可以将整个URI重定向到参数中,然后重定向到它(但是这种方法是不安全的,因为参数可能会被用户破坏)。

  • 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).

通常,我会选择第三个选项(参数),因为您对重定向过程有最好的控制(前两个选项依赖于HTTP引用,任何访问者都可以使用它,因此可能不安全)

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).

这篇关于控制器重定向到不同的路径,具体取决于上一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆