2
class Foo
  include Mongoid::Document

  field :bars, type:Array
end

How to validate that the bars array is not empty?

Ryan McGeary
  • 235,892
  • 13
  • 95
  • 104
B Seven
  • 44,484
  • 66
  • 240
  • 385

1 Answers1

4

Try the standard presence validator:

class Foo
  include Mongoid::Document

  field :bars, type: Array

  validates :bars, presence: true
end

This works because the presence validator uses the blank? method to check the attribute during validation.

Ryan McGeary
  • 235,892
  • 13
  • 95
  • 104
  • 1
    @BSeven You can always write your own validator that replicates `presence` (or inherits from it) and give it your own custom validator name. [Custom Validators](http://guides.rubyonrails.org/active_record_validations.html#custom-validators) are explained and covered well in the the Rails Guides. Pay specific attention to the `ActiveModel::EachValidator` option. – Ryan McGeary May 27 '15 at 20:11
  • @BSeven Also, arguably, `presence` is a perfect name. Consider `Array#present?` in ActiveSupport. – Ryan McGeary May 27 '15 at 20:14
  • @BSeven Why? Because `blank?`, `present?`, and `presence` methods are available on every single object in a Rails environment. It's been this way for ~10 years and a definition for the word "present" is "existing" (aka non-blank or non-empty). – Ryan McGeary May 27 '15 at 20:20
  • `present` sounds to me like not nil. Something like `unempty` would be more expressive. But I can see how `present` makes sense given the context of an array. – B Seven May 27 '15 at 21:06