Rails 5 redirect_back with url query parameter option


Rails 5 redirect_back with url query parameter option



According to the docs:





redirect_back(fallback_location:, allow_other_host: true, **args)


:fallback_location


Referer


:allow_other_host



And redirect_to allows me to add params to the url just by passing them as a hash


redirect_to



So, why do none of these work for me:




redirect_back fallback_location: tasks_path, allow_other_host: false, syncing: true


redirect_back fallback_location: tasks_path, allow_other_host: false, { syncing: true }


redirect_back fallback_location: tasks_path, allow_other_host: false, options: { syncing: true }


redirect_back(fallback_location: tasks_path, allow_other_host: false, options: { syncing: true })


redirect_back(fallback_location: tasks_path, allow_other_host: false, syncing: true)



...and any other iteration on the above that I could think of.



All of them (that are valid code), just return me back without the added parameter



I'm trying to achieve this URL:
(back_url or fallback_location) + '?syncing=true'


(back_url or fallback_location) + '?syncing=true'




2 Answers
2



If you look at the source code for redirect_back you will see, that it essentially uses redirect_to "whatever_url.com" version of redirect_to method.


redirect_back


redirect_to "whatever_url.com"


redirect_to



If you check the explanation of redirect_to you can see that in this use case you unfortunately cannot pass any arguments. If this is super needed, I guess you could just override the redirect_back method to append params option to the url with string concatenation, but that seems like a nasty fix.


redirect_back



But to answer your question - what you want to achieve seems to be impossible out of the box.



While I get what @Kkulikovskis is saying, I would argue that the docs are confusing as they suggest I can pass additional *args and have them respond as they would to redirect_to.


*args


redirect_to



So, I wrote a helper method:


def redirect_back_for_sync
if request.env['HTTP_REFERER'].present? &&
request.env['HTTP_REFERER'] != request.env['REQUEST_URI']
redirect_to request.env['HTTP_REFERER'] + '?syncing=true'
else
redirect_to properties_path(syncing: true)
end
end



Now I can call redirect_back_for_sync in my controller instead of using redirect_back at all.


redirect_back_for_sync


redirect_back






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API