You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dry-validation中允许含nil值的哈希数组?

dry-validations 允许哈希数组字段接受nil值的正确配置

你当前的验证规则required(:properties).maybe(:array).each(:hash)会触发NoMethodError,原因是当properties为nil时,后续的.each(:hash)会尝试对nil调用map方法(dry-logic的each操作内部依赖map)。

解决这个问题的核心是让each验证仅在字段值不为nil时执行,正确的配置有两种方式:

方式一:使用块语法包裹数组和元素验证

required(:properties).maybe do
  array.each(:hash)
end

方式二:链式传递组合验证规则

required(:properties).maybe(array.each(:hash))

以上两种配置的效果一致:

  • 当properties为nil时,验证直接通过
  • 当properties是数组时,会检查数组中的每个元素是否为哈希
  • 当properties是非nil且非数组的值时,验证失败

内容的提问来源于stack exchange,提问作者svelandiag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 08:07:03