ruby-on-rails - `rescue_from` 格式为json时异常

标签 ruby-on-rails ruby json

我在 Rails 中有一个应用程序可以同时响应 json 和 html。
我喜欢这样,当记录在保存时返回错误时,json 答案是这样的:

{
  "errors" : {
    "slug" : [
      "can't be blank"
    ],
    "title" : [
      "can't be blank"
    ]
  }
}

所以我将这段代码添加到我的 ApplicationController 类中。

rescue_from ActiveRecord::RecordInvalid do |exception|
  render json: { errors: exception.record.errors },
         status: :unprocessable_entity
end

我希望此 rescue_from 仅在格式为 json 时被调用,否则以标准方式运行(当格式为 html 时)。我怎样才能做这样的事情?

更新 我找到了一个解决方案,但我认为它不是很好:

rescue_from ActiveRecord::RecordInvalid do |exception|
  respond_to do |format|
    format.json do
      render json: { errors: exception.record.errors },
           status: :unprocessable_entity
    end
    format.html { fail exception }
  end
end

有没有更好的方法?

最佳答案

有更好的方法。

例如:

  rescue_from ActionController::InvalidAuthenticityToken do |exception|
    raise unless request.xhr?
    render nothing: true, status: :unprocessable_entity
  end

关于ruby-on-rails - `rescue_from` 格式为json时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939722/

相关文章:

ruby-on-rails - Rails has_secure_password 更改 BCrypt 成本因素(又名工作因素)

ruby - define_method 带有预定义的关键字参数

mysql - 如何使用 Node.js 设置用 mysql 数据库中的数据填充的 json 文件的名称?

ruby-on-rails - 一个模型中有多个状态机?

ruby-on-rails - rails : Export data in google spreadsheet

ruby-on-rails - Heroku预编译错误

ruby - 我在哪里可以获得 Centos OS 的 Ruby 1.8.6

ruby-on-rails - 在 Ruby 中,如何正确读取基准测试的结果?

c# - .NET 反序列化 JSON 时无法解析嵌套对象

javascript - NodeJS : HTTP response fired twice