Class: ExtraValidations::NestedValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/extra_validations/nested_validator.rb

Overview

Makes sure that the nested object is valid.

Suppose that you have the following class:

class Book
  include ActiveModel::Model
  include ExtraValidations

  attr_accessor :author

  validates :author, nested: true
end

This validator will call #valid? on the nested object:

book = Book.new
book.author = invalid_author
book.valid? # => false

book.author = valid_author
book.valid? # => true

Each validation error found will be appended on to the errors object:

book.errors.messages # => {:"author/name"=>["can't be blank"]}

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, nested) ⇒ Object

Parameters:

  • record

    An object that has ActiveModel::Validations included

  • attribute (Symbol)
  • nested

    An object that has ActiveModel::Validations included



32
33
34
35
36
37
38
# File 'lib/extra_validations/nested_validator.rb', line 32

def validate_each(record, attribute, nested)
  return if !nested || nested.valid?

  nested.errors.each do |nested_attr, error|
    record.errors.add("#{attribute}/#{nested_attr}", error)
  end
end