Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, e.g. redirect to:

/tasks/6?bar=1

Thanks!

like image 891
Peter Avatar asked Dec 13 '13 19:12

Peter


Video Answer


1 Answers

: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.

like image 50
Simone Carletti Avatar answered Sep 29 '22 20:09

Simone Carletti