【问题标题】:Redirecting from an update action to the referrer of the edit从更新操作重定向到编辑的引用者
【发布时间】:2010-03-13 05:08:02
【问题描述】:

我的 Rails 2.3 应用程序有一个用户模型和常用的控制器操作。可以通过两种方式访问​​编辑表单:当用户从主页编辑自己的个人资料时,或者当管理员用户从用户集合中编辑其他人的个人资料时。

我想做的是将更新操作重定向回编辑操作的引用,而不是更新操作。如果我在更新中做一个简单的redirect_to(:back),它会回到编辑表单——不好。

一种解决方案是完全忘记引荐来源网址并根据 current_user 和更新的用户进行重定向:如果它们相同,则返回主页,否则转到用户集合页面。如果我向编辑表单添加第三条路径,这将中断。我怀疑我是否会这样做,但我更喜欢一个不那么脆弱的解决方案。

另一种解决方案是将编辑表单的引用者存储在隐藏字段中,然后从更新操作内部重定向到该值。这感觉不太对劲,虽然我无法解释原因。

有没有更好的方法?或者,我应该停止担心并选择我提到的两个中的一个吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您可以记住会话中的 url。这就是我在我的应用程序中实现此功能的方式。

    将这些方法添加到您的 ApplicationController

    def store_location location=nil
        session[:return_to] = location || request.request_uri
    end
    
    def redirect_back_or_default(default)
        redirect_to(session[:return_to] || default)
        session[:return_to] = nil
    end
    
    def http_referrer
      http_referer, request_path  = request.env["HTTP_REFERER"], 
                                    request.env["REQUEST_PATH"]
      return nil  unless (http_referer and request_path and 
                          http_referer =~ Regexp.new("^#{SITE_ROOT}") and
                          http_referer != (SITE_ROOT + request_path))
      return http_referer    
    end
    

    UserController edit/new action 中存储引用者。

    before_filter :store_location, :only => [:new, :edit]
    
    def store_location
      super http_referrer
    end
    

    UserController create/update 操作中返回并重置引荐来源网址。

    def create
      if @user.save
        flash[:notice] = "Successfully created the user."
        redirect_back_or_default root_url
      else
        render :action => 'new'
      end
    end    
    
    def update
      if @user.save
        flash[:notice] = "Successfully created the user."
        redirect_back_or_default root_url
      else
        render :action => 'new'
      end
    end    
    

    【讨论】:

    • 如果网站在多个选项卡中打开,这将如何工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多