如何通过路由助手最轻松地转发参数?
这显然不起作用:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以轻松转发除要排除的参数之外的所有参数,如下所示:
但是,如果您有嵌套资源(您可能没有),这可能会让您仍然通过 :authenticity_token、:_method 和其他参数(例如 :id)发送想。
因此,对于大多数目的来说,这似乎是最简单的方法:
它可以让您简单地指定要发送的参数(它排除其余参数),而无需大量代码。
You could easily forward all parameters except the ones you want to exclude, like this:
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:
Which lets you simply specify the params you want to send through (it excludes the rest), without a lot of code.