How I can redirect not to html format but to json?
I want smthing like this:
redirect_to user_path(@user), format: :json
But this doesn't work, I still redirected to html path.
I read apidock some more... It was quite simple. I just should specify format in path helper like this:
redirect_to user_path(@user, format: :json)
The accepted answer (specifying format: :json
in the redirect_to
options) wasn't working for me in a Rails 5.2 API app; requests with an Accept: application/json
header.
Using redirect_to "/foo", format: :json
resulted in a response like this (edited for brevity):
HTTP/1.1 302 Found
Content-Type: text/html; charset=utf-8
Location: /foo
<html><body>You are being <a href="/foo">redirected</a>.</body></html>
This does not work for an API, so instead of using redirect_to
at all I switched to using head:
head :found, location: "/foo"
This results in the following response (again, edited for brevity) without a body, which is precisely what I was looking for:
HTTP/1.1 302 Found
Content-Type: application/json
Location: /foo
In my case I wasn't redirecting to a page in my Rails app, so I didn't use a URL helper, but if you are doing so (e.g. user_path
or redirect_to @user
) you can provide the relevant option to your URL helper like so:
head :found, location: user_path(user, format: :json)
# or
head :found, location: url_for(@user, format: :json)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With