Method: MassRecord::Actions#sql_for_update

Defined in:
lib/mass_record.rb

#sql_for_update(hash, into: nil) ⇒ Object



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/mass_record.rb', line 420

def sql_for_update hash, into:nil
  return nil if hash.blank? or into.blank?
  model = get_model from:into
  id_column_name = model.primary_key
  created_at = model.attribute_alias?("created_at") ? model.attribute_alias("created_at") : "created_at"
  updated_at = model.attribute_alias?("updated_at") ? model.attribute_alias("updated_at") : "updated_at"
  t = model.arel_table

  h = hash.clone # use a copy of hash, so it doesn't change the original data
  h = convert_to_db_format h, model:model, created_at:created_at, updated_at:updated_at

  # assemble an individual query
  # um = Arel::UpdateManager.new(ActiveRecord::Base)
  um = Arel::UpdateManager.new(model)
  um.where(t[id_column_name.to_sym].eq(h[id_column_name])) unless id_column_name.is_a? Array
  id_column_name.each{|key| um.where t[key.to_sym].eq(h[key])} if id_column_name.is_a? Array
  um.table(t)
  id_column_name.each{|name| h.delete name} if id_column_name.is_a? Array  # don't allow modification of the primary keys
  h.delete id_column_name if id_column_name.is_a? String           # don't allow modification of the primary keys
  pairs = h.collect do |k,v|
    [t[k.to_sym],v]
  end
  um.set pairs
  um.to_sql
end