ActiveRecord::Base -- dump to a SQL insert statement
Apr 16 2009 // Comments
So today I embarked on what I thought was going to be an easy task -- I needed to dump a few tables and rows from my Postgres database to raw SQL for transport to another system for testing. I didn't need to dump the whole database, nor did I need the whole table either. Unfortunately, pg_dump doesn't have a "query" parameter to filter the results.
After assuming AR would have such a graceful way to dump to raw sql (after all, that is exactly what it supposed to do), I couldn't for the life of me find a public method to accomplish a conversion to SQL. Thinking I'm just a dope and frustrated as my brain is fried, I did what any self-respecting programmer does -- start googling.
After awhile of googling and yielding zero solutions, I finally just decided to write a simple addition to the AR base class to allow me to dump a AR class to raw sql. It's not rocket science, nor is it robust in any shape or fashion, but it got the job done for me. I've included it here in case anyone out there has also run into this before and needs a quick solution.
Cheers!
class ActiveRecord::Base
def to_sql
"INSERT INTO #{self.class.quoted_table_name} (#{quoted_column_names.join(', ')}) VALUES(#{attributes_with_quotes.values.join(', ')})"
end
end

Ruby and Rails developer with extensive web development
background in various technologies. Active private pilot and
technology enthusiast always looking for excuse to fly.