Rails 4: redirect_to: back and change / delete parameters

I think it should be easy, but I can't get it to work in my life or find anything on the Internet that explains it. After submitting the form, I want to redirect back to the referrer / referrer and change or delete one or more request parameters.

For example, the form is in

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

And I want to go to

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

I tried all kinds of combinations based on

 redirect_to :back, foo: 0 

or

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

etc., but nothing would change me for anything other than the original page. I was hoping to avoid having to cripple the string, but this could happen.

It would be great if there was also a way to just get rid of the parameter as a whole, for example. redirect to:

 /tasks/6?bar=1 

Thanks!

+6
source share
1 answer

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

 request.referer 

or

 request.env['HTTP_REFERER'] 

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

You can update the hash and create a redirect URL.

+4
source

All Articles