【问题标题】:How to validate that an array is not empty in Mongoid?如何验证 Mongoid 中的数组不为空?
【发布时间】:2015-05-27 03:23:07
【问题描述】:
class Foo
  include Mongoid::Document

  field :bars, type:Array
end

如何验证bars数组不为空?

【问题讨论】:

    标签: ruby-on-rails ruby mongoid activemodel activesupport


    【解决方案1】:

    试试标准的presence验证器:

    class Foo
      include Mongoid::Document
    
      field :bars, type: Array
    
      validates :bars, presence: true
    end
    

    这是因为presence 验证器使用blank? 方法在验证期间检查属性。

    【讨论】:

    • @BSeven 你总是可以编写自己的验证器来复制presence(或从它继承)并给它你自己的自定义验证器名称。 Custom Validators 在 Rails 指南中得到了很好的解释和介绍。请特别注意ActiveModel::EachValidator 选项。
    • @BSeven 另外,可以说,presence 是一个完美的名字。考虑 ActiveSupport 中的Array#present?。
    • @BSeven 为什么?因为 blank?、present? 和 presence 方法可用于 Rails 环境中的每个对象。这种方式已经有 10 年了,“现在”这个词的定义是“存在”(也就是非空白或非空)。
    • present 在我看来不是零。像unempty 这样的东西会更有表现力。但我可以看到present 在给定数组上下文的情况下是如何有意义的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多