ruby-on-rails - Rails 无法读取以 "false"值作为属性的 JSON 请求

标签 ruby-on-rails ruby json

嗯,我正在使用 Rails 4.2.6 和 ruby​​ 2.3.0 构建 RESTfull API。 我有一个 :programs 资源,每当我尝试通过 Google Postman 发出 POST 请求时,都会收到“不能为空”错误。 等等,让我举例说明...

当我通过 postman 发送此信息时:

{
  "program": {
    "expiration_points": "false"
  }
}

我要回复这个:

{
  "errors": {
    "expiration_points": [
      "can't be blank"
    ]
  }
}

我已经尝试过:“false”、“false”、false 和 :false。

但当我使用“true”或 expiration_points 的 true 值发出 POST 请求时,它工作正常。

请记住,我在迁移时为 expiration_points 属性定义了一个 default: false 值。

所以...问题是,我做错了什么?顺便说一句,谢谢。

最佳答案

所以你的模型中有这个:

validates :expiration_points, presence: true 

那么presence: true有什么作用呢?我们可以检查validates documentation但这只是说:

This method is a shortcut to all default validators and any custom validator classes ending in 'Validator'. Note that Rails default validators can be overridden inside specific classes by creating custom validator classes in their place such as PresenceValidator.
[...]

但这只是给了我们一堆例子,并告诉我们一些选项的作用。您可以查找 PresenceValidator 文档,但没有这样的东西。

如果您已经使用 Rails 一段时间,您就会知道

validate :f, :presence => true

在功能上等同于:

validates_presence_of :f

validates_presence_of documentation仍然存在:

Validates that the specified attributes are not blank (as defined by Object#blank?).
[...]
If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use validates_inclusion_of :field_name, in: [true, false].

This is due to the way Object#blank? handles boolean values: false.blank? # => true.

所以你根本不需要 presence: true ,你想使用 in: [ true, false ] 来代替:

validate :expiration_points, :in => [ true, false ]

关于ruby-on-rails - Rails 无法读取以 "false"值作为属性的 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706555/

相关文章:

ruby-on-rails - Rails 如何检查尚未实例化的类是否存在?

javascript - 没有 Javascript 的 capybara Click_Button 失败

ruby - 从 Ruby 中的用户输入字符串中提取多个整数?

ruby-on-rails - 模型中匹配所有关联值的方法

json - 我无法使用从请求中获取的数据创建结构

java - Android:捕获结果但 json 值显示在 LogCat 中

ruby-on-rails - 如何从类方法返回未更改的 AR 关系

ruby-on-rails - 在 Rails ActiveRecord 测试套件中使用 Ruby 1.9 lambda 文字感到困惑

ruby - 为什么没有更多的项目使用 Ruby Symbols 而不是 Strings?

json - 使用 jq 处理巨大的 json 数组文件