当referrer不可用时,正确地执行redirect_to:返回Ruby on Rails [英] Correctly doing redirect_to :back in Ruby on Rails when referrer is not available

查看:497
本文介绍了当referrer不可用时,正确地执行redirect_to:返回Ruby on Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 redirect_to:back 的问题。是的,它是推荐人。



我经常得到异常


(ActionController: :RedirectBackError)在此操作的请求中未设置HTTP_REFERER,因此无法成功调用redirect_to:back。如果这是测试,请确保指定request.env [\HTTP_REFERER \]。


我发现这是推荐人无法使用的结果。有没有办法,例如,可以在访问的最后一页访问每次访问时设置会话变量,并且,当HTTP_REFERER不可用时,利用此会话变量重定向到?

解决方案



没有设置推荐人的情况并不常见,我通常会拯救这种期望:

  def some_method 
redirect_to:back
rescue ActionController :: RedirectBackError
redirect_to root_path
end

如果你经常这样做(我认为这是一个坏主意)你可以用Maran建议的其他方法包装它。



BTW我认为这是一个坏主意,因为这会使用户流模糊不清。只有在登录的情况下这才是明智的。



更新:有几个人指出这个不再有效。
相反,使用 redirect_back ,这种方法也支持回退。然后代码成为:

  def some_method 
redirect_back fallback_location:root_path
end


I'm having a problem with redirect_to :back. Yes, it's referrers.

I often get the exception

(ActionController::RedirectBackError) "No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env[\"HTTP_REFERER\"]."

I realize that this is a result of a referrer not being available. Is there a way that, for example, one can set a session variable on each access with the last page visited, and, when HTTP_REFERER is not available, utilize this session variable to redirect to?

解决方案

It is unlikely that you do have a session and don't have a referrer.

The situation that a referrer is not set isn't that uncommon and I usually rescue that expection:

def some_method
  redirect_to :back
rescue ActionController::RedirectBackError
  redirect_to root_path
end

If you do this often (which I think is a bad idea) you can wrap it in an other method like Maran suggests.

BTW I think that's a bad idea because this makes the userflow ambiguous. Only in the case of a login this is sensible.

UPDATE: As several people pointed out this no longer works with Rails 5. Instead, use redirect_back, this method also supports a fallback. The code then becomes:

def some_method
  redirect_back fallback_location: root_path
end

这篇关于当referrer不可用时,正确地执行redirect_to:返回Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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