Sha256: 3170d1a5a94018c62617b90967553c5b6277555e70156d49ea7d91a2e27e03a6

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

module Torque
  module PostgreSQL
    module AutosaveAssociation
      module ClassMethods
        def add_autosave_association_callbacks(reflection)
          return super unless reflection.macro.eql?(:belongs_to_many)

          save_method = :"autosave_associated_records_for_#{reflection.name}"
          define_non_cyclic_method(save_method) { save_belongs_to_many_array(reflection) }

          if PostgreSQL::AR610
            around_save(:around_save_collection_association)
          else
            before_save(:before_save_collection_association)
            after_save(:after_save_collection_association) if ::ActiveRecord::Base
              .instance_methods.include?(:after_save_collection_association)
          end

          before_create(save_method)
          before_update(save_method)

          define_autosave_validation_callbacks(reflection)
        end
      end

      def save_belongs_to_many_array(reflection)
        save_collection_association(reflection)

        association = association_instance_get(reflection.name)
        return unless association

        klass_attr = reflection.active_record_primary_key
        source_attr = reflection.foreign_key

        records = association.target.each_with_object(klass_attr)
        write_attribute(source_attr, records.map(&:read_attribute).compact)
      end
    end

    ::ActiveRecord::Base.singleton_class.prepend(AutosaveAssociation::ClassMethods)
    ::ActiveRecord::Base.include(AutosaveAssociation)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
torque-postgresql-2.0.4 lib/torque/postgresql/autosave_association.rb