Rails7:如何将变量从一个控制器传递到下一个控制器

Rails 7: How to pass a variable from one controller to the next

在 Rails 中,过去可以通过调用类似以下内容将变量(此处::anchor)从一个控制器传递到下一个控制器:

redirect_to user_profile_path(anchor: 'details')

但试图在下一个控制器中捕获 :anchor,即像这样...

puts params[:anchor].inspect
puts request.params[:anchor].inspect

...失败。为什么?

(我在 Rails 7,以防万一。)

编辑:

奇怪的是,当我使用不同的 key,即 test...

redirect_to user_profile_path(anchor: 'details', test: 'test-value')

...然后...

puts params[:test].inspect

...正确 returns 日志文件中的值:

'test-value'

这与 Rails 关系不大,而与浏览器和 URI 的工作方式关系更大。

Anchor 是 url_for for that adds a URI Fragment (aka anchor or hash) 到 URL 的特殊选项。

客户端在请求 URI 时不会将 URI 片段发送到服务器。它在设计上对服务器透明。但是客户端会接受来自服务器的片段。

如果您想在 GET 请求中将附加信息从客户端传递到服务器,您需要通过添加查询字符串参数、自定义 headers 或 cookie 来实现。

使用 user_profile_path(anchor: 'details', test: 'test-value') 有效,因为 test: 不是命名选项,而是添加查询字符串参数。