Module: Switchman::ActiveRecord::Associations::AutosaveAssociation

Defined in:
lib/switchman/active_record/associations.rb

Instance Method Summary collapse

Instance Method Details

#association_foreign_key_changed?(reflection, record, key) ⇒ Boolean



262
263
264
265
266
267
268
269
270
# File 'lib/switchman/active_record/associations.rb', line 262

def association_foreign_key_changed?(reflection, record, key)
  return false if reflection.through_reflection?

  foreign_key = Array(reflection.foreign_key)
  return false unless foreign_key.all? { |k| record._has_attribute?(k) }

  # have to use send instead of _read_attribute because sharding
  foreign_key.map { |k| record.send(k) } != Array(key)
end

#save_belongs_to_association(reflection) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/switchman/active_record/associations.rb', line 272

def save_belongs_to_association(reflection)
  association = association_instance_get(reflection.name)
  return unless association&.loaded? && !association.stale_target?

  record = association.load_target
  return unless record && !record.destroyed?

  autosave = reflection.options[:autosave]

  if autosave && record.marked_for_destruction?
    foreign_key = Array(reflection.foreign_key)
    foreign_key.each { |key| self[key] = nil }
    record.destroy
  elsif autosave != false
    saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)

    if association.updated?
      primary_key = Array(compute_primary_key(reflection, record)).map(&:to_s)
      foreign_key = Array(reflection.foreign_key)

      primary_key_foreign_key_pairs = primary_key.zip(foreign_key)
      primary_key_foreign_key_pairs.each do |pk, fk|
        # Notable change: add relative_id_for here
        association_id = if record.class.sharded_column?(pk)
                           Shard.relative_id_for(
                             record._read_attribute(pk),
                             record.shard,
                             shard
                           )
                         else
                           record._read_attribute(pk)
                         end
        self[fk] = association_id unless self[fk] == association_id
      end
      association.loaded!
    end

    saved if autosave
  end
end