如何通过路由助手最轻松地转发参数?

发布于 2024-11-06 15:43:28 字数 493 浏览 1 评论 0原文

这显然不起作用:

redirect_to post_path(@post, :params => params)

因为 Rails 路由助手不允许您直接设置参数哈希(根据我读到的内容)。

这可能会带来一些问题:

redirect_to post_path(@post, params)

因为您也会转发 :controller 和 :action 参数,这会将您带到您来自的相同控制器和操作。这通常不是您想要的。

这可行,但还不够,因为它很麻烦,因为需要大量代码将所有参数(除了 :action 和 :controller)设置为现有参数:

redirect_to post_path(@post, {:someparameter => params[:someparameter]})

那么,最简​​单和最简单的方法是什么?

This apparently doesn't work:

redirect_to post_path(@post, :params => params)

Since Rails route helpers doesn't allow you to set the params hash directly (from what I've read).

This could pose some problems:

redirect_to post_path(@post, params)

Since you would be forwarding :controller and :action parameters as well, which would take you to the same controller and action you came from. This is often not what you want.

This works, but is insufficient, since it is cumbersome in that it takes a lot of code to set all the params (except :action and :controller) to the existing params:

redirect_to post_path(@post, {:someparameter => params[:someparameter]})

So, what is the simplest and easiest way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅忆 2024-11-13 15:43:28

您可以轻松转发除要排除的参数之外的所有参数,如下所示:

redirect_to post_path(@post, params.to_hash.except(:controller, :action))

但是,如果您有嵌套资源(您可能没有),这可能会让您仍然通过 :authenticity_token、:_method 和其他参数(例如 :id)发送想。

因此,对于大多数目的来说,这似乎是最简单的方法:

redirect_to post_path(@post, params.to_hash.slice(:someparameter, :anotheparameteryouwant))

它可以让您简单地指定要发送的参数(它排除其余参数),而无需大量代码。

You could easily forward all parameters except the ones you want to exclude, like this:

redirect_to post_path(@post, params.to_hash.except(:controller, :action))

But that would probably leave you with still sending through :authenticity_token, :_method, and other parameters like :id if you have a nested resource, which you might not want.

Therefore, it seems that this is the easiest way, for most purposes is:

redirect_to post_path(@post, params.to_hash.slice(:someparameter, :anotheparameteryouwant))

Which lets you simply specify the params you want to send through (it excludes the rest), without a lot of code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文