Skip to content

Instantly share code, notes, and snippets.

@gisborne
Created May 6, 2010 23:44
Show Gist options
  • Save gisborne/392833 to your computer and use it in GitHub Desktop.
Save gisborne/392833 to your computer and use it in GitHub Desktop.

Revisions

  1. gisborne created this gist May 6, 2010.
    11 changes: 11 additions & 0 deletions Concise SQL generation
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    def self.create_from_array(attrs)

    keys = attrs.first.keys
    
 d = ActiveRecord::Base.connection

    d.execute <<SQL

    INSERT INTO #{table_name} (#{keys * ', '}, created_at, updated_at)
    
 VALUES #{attrs.map do |a|
      "(#{keys.map{|k| d.quote(a[k].to_s)} * ','},

        NOW(),

              NOW())"}

    ON DUPLICATE KEY UPDATE #{keys.map{|k| "#{k} = VALUES(#{k})"} * ', '}
    
SQL
    
end