问题描述
我遇到了 redirect_to:back
的问题。是的,它是推荐人。
我经常得到异常
我发现这是推荐人无法使用的结果。有没有办法,例如,可以在访问的最后一页访问每次访问时设置会话变量,并且,当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
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!