class Mongoid::Validatable::CollectionSizeValidator

Validates that the specified collections do or do not match a certain size.

@example Set up the collection size validator.

class Person
  include Mongoid::Document
  has_many :addresses

  validates_collection_size_of :addresses, in: 1..10
end

Public Instance Methods

validate_each(record, attribute, value) click to toggle source
Calls superclass method
# File lib/custom_fields/extensions/mongoid/validatable/collection_size.rb, line 17
def validate_each(record, attribute, value)
  value = collection_to_size(record, attribute)

  super(record, attribute, value)
end

Private Instance Methods

collection_to_size(record, attribute) click to toggle source
# File lib/custom_fields/extensions/mongoid/validatable/collection_size.rb, line 25
def collection_to_size(record, attribute)
  # TODO: find an example with a has_and_belongs_to_many relationship...
  # relation = record.relations[attribute.to_s]

  # source = case relation.macro
  # when :embeds_many, :has_many
  #   record.send(attribute)
  # when :has_and_belongs_to_many
  #   record.send(relation.key.to_sym)
  # end

  source = record.send(attribute)

  OpenStruct.new(length: source.try(:size) || 0)
end