简体   繁体   中英

Rails 4: redirect_to :back and change/delete parameters

I think this should be easy but I cannot for the life of me get it to work, or find anything on the web that explains it. After a form submit, I want to redirect back to the referer/referrer and alter or delete one or more of the query parameters.

For example, the form is at

/tasks/6?foo=1&bar=1

And I want to go afterwards to

/tasks/6?foo=0&bar=1

I tried all sorts of combinations based on

redirect_to :back, foo: 0

or

redirect_to :back, params: {foo: 0, bar: 1}

and so on, but nothing at all would redirect me to anything other than the original page. I was hoping to avoid having to mangle with the string myself, but it may come to that.

It would be awesome, too, if there were also a way to just get rid of a parameter altogether, eg redirect to:

/tasks/6?bar=1

Thanks!

:back does not accept other arguments. In order to accomplish what you want to do, you need to get the value of the referrer using

request.referer

or

request.env['HTTP_REFERER']

Parse it with the URI library, extract the query and decompose it with Rack::Utils.parse_query . At this point you have the hash of params.

You can update the hash, and construct the URL for the redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM