【发布时间】:2015-05-27 03:23:07
【问题描述】:
class Foo
include Mongoid::Document
field :bars, type:Array
end
如何验证bars数组不为空?
【问题讨论】:
标签: ruby-on-rails ruby mongoid activemodel activesupport
class Foo
include Mongoid::Document
field :bars, type:Array
end
如何验证bars数组不为空?
【问题讨论】:
标签: ruby-on-rails ruby mongoid activemodel activesupport
试试标准的presence验证器:
class Foo
include Mongoid::Document
field :bars, type: Array
validates :bars, presence: true
end
这是因为presence 验证器使用blank? 方法在验证期间检查属性。
【讨论】:
presence(或从它继承)并给它你自己的自定义验证器名称。 Custom Validators 在 Rails 指南中得到了很好的解释和介绍。请特别注意ActiveModel::EachValidator 选项。
presence 是一个完美的名字。考虑 ActiveSupport 中的Array#present?。
blank?、present? 和 presence 方法可用于 Rails 环境中的每个对象。这种方式已经有 10 年了,“现在”这个词的定义是“存在”(也就是非空白或非空)。
present 在我看来不是零。像unempty 这样的东西会更有表现力。但我可以看到present 在给定数组上下文的情况下是如何有意义的。