Module: Changebase::Inline::Through

Extended by:
ActiveSupport::Concern
Defined in:
lib/changebase/inline/active_record.rb

Instance Method Summary collapse

Instance Method Details

#delete_records(records, method) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/changebase/inline/active_record.rb', line 8

def delete_records(records, method)
  x = super

  if method != :destroy
    records.each do |record|
      through_model = source_reflection.active_record

      columns = through_model.columns.each_with_index.reduce([]) do |acc, (column, index)|
        attr_type = through_model.type_for_attribute(column.name)
        previous_value = attr_type.serialize(column.name == source_reflection.foreign_key ? record.id : owner.id)
        acc << {
          index: index,
          identity: true,
          name: column.name,
          type: column.sql_type,
          value: nil,
          previous_value: previous_value
        }
        acc
      end

      transaction = through_model.connection.changebase_transaction || Changebase::Inline::Transaction.new(
        timestamp: Time.current,
        metadata: through_model.connection.instance_variable_get(:@changebase_metadata)
      )

      transaction.event!({
        schema: columns[0].try(:[], :schema) || through_model.connection.current_schema,
        table: through_model.table_name,
        type: :delete,
        columns: columns,
        timestamp: Time.current
      })

      # Save the Changebase::Transaction if we are not in a transaction.
      transaction.save! if !through_model.connection.changebase_transaction
    end
  end

  x
end