Method: ActiveHistory::Adapter::ActiveRecord#activehistory_association_udpated

Defined in:
lib/activehistory/adapters/active_record.rb

#activehistory_association_udpated(reflection, id, added: [], removed: [], timestamp: nil, type: :update) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/activehistory/adapters/active_record.rb', line 227

def activehistory_association_udpated(reflection, id, added: [], removed: [], timestamp: nil, type: :update)
  return if !activehistory_tracking || (removed.empty? && added.empty?)
  klass = reflection.active_record
  inverse_klass = reflection.klass
  
  inverse_association = if activehistory_tracking.has_key?(:habtm_model)
    inverse_klass.reflect_on_association(activehistory_tracking.dig(:habtm_model, reflection.name.to_s.singularize.to_sym, :inverse_of))
  else
    reflection.inverse_of
  end
  
  if inverse_association.nil?
    puts "NO INVERSE for #{self.class}.#{reflection.name}!!!"
    return
  end
  
  action = activehistory_event.action_for(klass, id, {
    type: type,
    timestamp: timestamp
  })
  
  action.diff ||= {}
  if (reflection.collection? || activehistory_tracking[:habtm_model])
    diff_key = "#{reflection.name.to_s.singularize}_ids"
    action.diff[diff_key] ||= [[], []]
    action.diff[diff_key][0] |= removed
    action.diff[diff_key][1] |= added
  else
    diff_key = "#{reflection.name.to_s.singularize}_id"
    action.diff[diff_key] ||= [removed.first, added.first]
  end
  
  removed.each do |removed_id|
    action = activehistory_event.action_for(inverse_klass, removed_id, {
      type: type,
      timestamp: timestamp
    })
  
    action.diff ||= {}
    if inverse_association.collection? || activehistory_tracking[:habtm_model]
      diff_key = "#{inverse_association.name.to_s.singularize}_ids"
      action.diff[diff_key] ||= [[], []]
      action.diff[diff_key][0] |= [id]
    else
      diff_key = "#{inverse_association.name.to_s.singularize}_id"
      action.diff[diff_key] ||= [id, nil]
    end
  end
  
  added.each do |added_id|
    action = activehistory_event.action_for(inverse_klass, added_id, {
      type: type,
      timestamp: timestamp
    })
  
    action.diff ||= {}
    if inverse_association.collection? || activehistory_tracking[:habtm_model]
      diff_key = "#{inverse_association.name.to_s.singularize}_ids"
      action.diff[diff_key] ||= [[], []]
      action.diff[diff_key][1] |= [id]
    else
      diff_key = "#{inverse_association.name.to_s.singularize}_id"
      action.diff[diff_key] ||= [nil, id]
    end
  end
end