Class: ExtraValidations::CollectionValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ExtraValidations::CollectionValidator
- Defined in:
- lib/extra_validations/collection_validator.rb
Overview
Makes sure that each member of the collection is a valid object.
Suppose that you have the following class:
class Book
include ActiveModel::Model
include ExtraValidations
attr_accessor :authors
validates :authors, collection: true
end
This validator will call #valid?
for each member of the collection:
book = Book.new
book. = [, ]
book.valid? # => false
book. = [, ]
book.valid? # => true
Each validation error found on members will be appended on to the errors object:
book.errors. # => {:"authors/1/name"=>["can't be blank"]}
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, collection) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/extra_validations/collection_validator.rb', line 34 def validate_each(record, attribute, collection) return if collection.blank? collection .each(&:valid?) .each_with_index do |obj, i| obj.errors.each do |attr, error| record.errors.add("#{attribute}/#{i}/#{attr}", error) end end end |