基本上我有以下 Controller 方法:
def create
begin
@check_in = create_check_in()
rescue => exception
render json: { message: exception }, status: 500
end
end
以及以下 json.rabl 文件:
object @check_in => :event_check_in
attributes :id
我试图实现的是手动设置响应的HTTP状态代码。它当前响应为 200,而我需要它为 201。
我很少看到类似的问题,答案通常是从 Controller 操作中渲染/respond_with,所以我尝试了这样的方法:
def create
begin
@check_in = create_check_in()
render @check_in, status: 201
rescue => exception
render json: { message: exception }, status: 500
end
end
但是我所有的尝试都失败了,抛出了各种错误。
有办法设置状态代码吗?
最佳答案
问题是您将 @check_in
作为 render
方法的第一个参数传递,而该方法期望第一个参数是选项的哈希值,包括状态
选项。
您的 status: 201
选项作为哈希值传递到方法的第二个参数并被忽略。
通常渲染调用将类似于:
render json: @check_in.as_json, status: 201
# or more commonly something like
render action: :create, status: 201 # the @check_in variable is already accessible to the view and doesn't need to be passed in
# or just
render status: 201
# since by default it will render the view with the same name as the action - which is `create`.
调用render的方法有很多,see the docs for more .
-- 编辑-- Max 有一个很好的评论 - 我强烈建议不要从所有异常中进行救援,也不要在特定的 Controller 操作中执行此操作。除了他的建议之外,Rails 5+ supports :api formatting for exceptions开箱即用,或者,如果您需要更多,我会查看指南 like this one .
关于ruby-on-rails - rails RABL : how to respond with specified http status code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68926946/