Skip to content

Instantly share code, notes, and snippets.

@HotFusionMan
Last active December 11, 2015 04:09
Show Gist options
  • Save HotFusionMan/4543333 to your computer and use it in GitHub Desktop.
Save HotFusionMan/4543333 to your computer and use it in GitHub Desktop.
ActiveRecord::Base instances don't know how to dump themselves out as SQL. Here's a method to do so (tested only for PostgreSQL).
class ActiveRecord::Base
def to_sql
columns = self.class.columns
values_list = []
columns.each do |column|
value = self.__send__( column.name.to_sym )
case column.type
when :string, :text, :datetime, :timestamp, :time, :date
unless value.nil?
value = "'#{value}'".gsub( /([^'])'([^'])/ ){ |match| "#{$1}''#{$2}" }
# PostgreSQL supports C-style string escape sequences like so:
if /[[:cntrl:]]/ =~ value
value.insert( 0, 'E' )
end
end
end
value = 'NULL' if value.nil?
values_list << value
end
"INSERT INTO #{self.class.table_name} (#{columns.map(&:name).join(', ')}) VALUES (#{values_list.join( ', ' )});"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment