我正在尝试在我的应用程序中使用redirect_back_or_to,我们最近升级到Rails 7,但它永远不会重定向到引荐来源网址,总是重定向到后备位置。
这就是我的控制器中的代码的样子:
def set_theme
if params[:theme]
current_user.settings(:appearance).theme = params[:theme]
current_user.save!
end
redirect_back_or_to timeline_path
end
我尝试这样做:
def set_theme
if params[:theme]
current_user.settings(:appearance).theme = params[:theme]
current_user.save!
end
redirect_to request.referer || timeline_path
end
这按预期工作。
所以,然后我查看了 Rails 源代码,并将整个
redirect_back_or_to
方法代码复制到我的代码中(不带选项):
def set_theme
if params[:theme]
current_user.settings(:appearance).theme = params[:theme]
current_user.save!
end
allow_other_host = false
if request.referer && (allow_other_host || _url_host_allowed?(request.referer))
redirect_to request.referer, allow_other_host: allow_other_host
else
# The method level `allow_other_host` doesn't apply in the fallback case, omit and let the `redirect_to` handling take over.
redirect_to timeline_path
end
end
这也有效!
我不明白这里发生了什么以及为什么当我调用该方法本身时它不起作用。我可以在需要时重定向到引用者,但我想使用该函数,因为它已经存在。
我刚刚遇到了这个问题。就我而言,我使用的 Sourcery Gem 版本定义了它自己的
redirect_back_or_to
版本,覆盖了预期的行为。