Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how to set json format for redirect_to

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.

like image 575
freemanoid Avatar asked Mar 08 '13 22:03

freemanoid


2 Answers

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)
like image 110
freemanoid Avatar answered Nov 08 '22 00:11

freemanoid


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)
like image 2
coreyward Avatar answered Nov 07 '22 22:11

coreyward