Module: ActiveModel::Validations::HelperMethods

Defined in:
lib/nested_validator/nested_validator.rb

Instance Method Summary collapse

Instance Method Details

#validates_nested(*attr_names) ⇒ Object

Bases an object’s validity on nested attributes.

class Parent < ActiveRecord::Base
  has_one :child

  validates_nested :child
end

class Child < ActiveRecord::Base
  attr_accessor :attribute
  validates     :attribute, presence: true

  validates_presence_of :attribute
end

Any errors in the child will be copied to the parent using the child’s name as a prefix for the error:

puts parent.errors.messages #=> { :'child attribute' => ["can't be blank"] }

Parameters:

  • attr_names

    attribute names followed with options

Options Hash (*attr_names):

  • :prefix (String)

    The prefix to use instead of the attribute name

  • :only (String, Array)

    The name(s) of attr_names to include when validating. Default is all

  • :except (String, Array)

    The name(s) of attr_names to exclude when validating. Default is none

  • :on (Symbol)

    Specifies when this validation is active. Runs in all validation contexts by default (nil), other options are :create and :update.

  • :if (Symbol, String or Proc)

    a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

  • :unless ([Symbol, String or Proc])

    a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

  • :strict (boolean)

    Specifies whether validation should be strict. See ActiveModel::Validation#validates! for more information.

See Also:



133
134
135
# File 'lib/nested_validator/nested_validator.rb', line 133

def validates_nested(*attr_names)
  validates_with NestedValidator, _merge_attributes(attr_names)
end