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屋!