Rails: how to set json format for redirect_to
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)