Rails: how to set json format for redirect_to

邮差的信 提交于 2020-12-08 05:51:46

问题


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.


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/15304073/rails-how-to-set-json-format-for-redirect-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!