instance method add_autosave_association_callbacks

Ruby on Rails 3.0.20

Since v2.3.18 Last seen in v4.2.9 Private

Available in: v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9

Signature

add_autosave_association_callbacks(reflection)

Adds validation and save callbacks for the association as specified by the reflection.

For performance reasons, we don’t check whether to validate at runtime. However the validation and callback methods are lazy and those methods get created when they are invoked for the very first time. However, this can change, for instance, when using nested attributes, which is called after the association has been defined. Since we don’t want the callbacks to get defined multiple times, there are guards that check if the save or validation methods have already been defined before actually defining them.

Parameters

reflection req
Source
# File activerecord/lib/active_record/autosave_association.rb, line 171
      def add_autosave_association_callbacks(reflection)
        save_method = :"autosave_associated_records_for_#{reflection.name}"
        validation_method = :"validate_associated_records_for_#{reflection.name}"
        collection = reflection.collection?

        unless method_defined?(save_method)
          if collection
            before_save :before_save_collection_association

            define_method(save_method) { save_collection_association(reflection) }
            # Doesn't use after_save as that would save associations added in after_create/after_update twice
            after_create save_method
            after_update save_method
          else
            if reflection.macro == :has_one
              define_method(save_method) { save_has_one_association(reflection) }
              after_save save_method
            else
              define_non_cyclic_method(save_method, reflection) { save_belongs_to_association(reflection) }
              before_save save_method
            end
          end
        end

        if reflection.validate? && !method_defined?(validation_method)
          method = (collection ? :validate_collection_association : :validate_single_association)
          define_method(validation_method) { send(method, reflection) }
          validate validation_method
        end
      end

Defined in activerecord/lib/active_record/autosave_association.rb line 171 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveRecord::AutosaveAssociation::ClassMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close