Method: MassRecord::Actions#sql_for_insert

Defined in:
lib/mass_record.rb

#sql_for_insert(hash, into: nil) ⇒ Object



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/mass_record.rb', line 395

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

  # assemble an individual query
  # im = Arel::InsertManager.new(ActiveRecord::Base)
  im = Arel::InsertManager.new(model)
  unless id_column_name.is_a? Array  # don't modify the id fields if there are concatenated primary keys
    database_column = model.columns.select{|x| x.name == id_column_name}.first
    h.delete id_column_name if h[id_column_name].blank? or (database_column.methods.include? :extra and database_column.extra == 'auto_increment')
  end
  h = convert_to_db_format h, model:model, created_at:created_at, updated_at:updated_at
  pairs = h.collect do |k,v|
    [t[k.to_sym],v]
  end
  im.insert pairs
  im.to_sql
end