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|
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
|