gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:19 25 4
gpt4 key购买 nike

嗯,我正在使用 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。

但是当我使用 expiration_points 的“true”或 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com