开发者

How to most easily forward params through a route helper?

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:

redi开发者_StackOverflowrect_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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜