嗯,我正在使用 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 aretrue
andfalse
), you will want to usevalidates_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/