Last active
December 11, 2015 04:09
-
-
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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