Class: SimpleActiveModelValidators::AssociatedBubblingValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/simple_activemodel_validators/associated_bubbling_validator.rb

Overview

Bubbles up associated validation errors on to the main model. For example

class User < ActiveRecord::Base
  validates :name, presence: true
  has_many :comments
  validates_with SimpleActiveModelValidators::AssociatedBubblingValidator, attributes: [:comments]
end

class Comment < ActiveRecord::Base
  belongs_to :user
  validates :body, presence: true
end

user = User.new(name: 'Joe', comments: [Comment.new(body: '')])
user.valid?
user.errors.messages == { comments: ["is invalid", { body: ["can't be blank"] }] }

Similar to validates_associated with the extra error bubbling feature.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, values) ⇒ Object

Implements the contract of ActiveModel::EachValidator

Parameters:

  • record

    The record being validated

  • attribute

    The name of the attribute being validated

  • values

    The value of the attribute

Returns:

  • nil



29
30
31
32
33
34
# File 'lib/simple_activemodel_validators/associated_bubbling_validator.rb', line 29

def validate_each(record, attribute, values)
  # values can be an array or a scalar
  [values].flatten.compact.reject(&:valid?).each do |value|
    record.errors.add(attribute, value.errors.messages)
  end
end