Rails 4 - 无论请求的格式如何,如何呈现 JSON? [英] Rails 4 - How to render JSON regardless of requested format?
问题描述
我想要一个 Rails 控制器(实际上,它们都是一个 API)来始终呈现 JSON.
I'd like a Rails controller (all of them, actually, it's an API) to render JSON always always.
我不希望 Rails 返回找不到路由",或者尝试但找不到 HTML 模板,或者返回 406.我只希望它自动并始终呈现 JSON,例如从 RABL 或 JBuilder 视图.
I don't want Rails to return "route not found", or try and fail to find an HTML template, or return 406. I just want it to automatically and always render JSON, e.g. from a RABL or JBuilder view.
这可能吗?相关问题的答案似乎具有上述缺点.
Is this possible? Related questions seem to have answers that have the aforementioned downsides.
推荐答案
你可以在你的控制器中添加一个before_filter
来设置请求格式为json
:
You can add a before_filter
in your controller to set the request format to json
:
# app/controllers/foos_controller.rb
before_action :set_default_response_format
protected
def set_default_response_format
request.format = :json
end
这会将所有响应格式设置为 json
.如果您想允许其他格式,您可以在设置 request.format
时检查是否存在 format
参数,例如:
This will set all response format to json
. If you want to allow other formats, you could check for the presence of format
parameter when setting request.format
, for e.g:
def set_default_response_format
request.format = :json unless params[:format]
end
这篇关于Rails 4 - 无论请求的格式如何,如何呈现 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!