ruby-on-rails - rails RABL : how to respond with specified http status code?

标签 ruby-on-rails rabl

基本上我有以下 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/

相关文章:

ruby-on-rails - 在 Rails 的父显示页面中显示子数据

ruby-on-rails - Rails rabl - 返回所有属性,而不仅仅是命名属性

ruby-on-rails - Rabl json 集合动态键

ruby-on-rails - 有没有办法设置一个假的电子邮件收件箱来检查电子邮件是否在 ruby​​ on rails 中发送?

css - 从 Foundation - Rails 更改选项卡名称

ruby-on-rails - 如何在一行中使用 if 语句在 Ruby 中设置变量?

ruby-on-rails - 在 Rails 中使用 RABL 渲染简单的 JSON 数组

ruby-on-rails - 如何通过保持约定来重用 RABL 部分模板?

ruby-on-rails - Rails 在命名空间模型后找不到表