Last Updated: February 25, 2016
·
11.77K
· lankz

How to generate ActiveRecord insert SQL

I came up with this a while back in response to a question asked on Twitter. I just came across it after being asked about it again, yet I've never had a use for it myself.

This will give you the SQL INSERT statement generated by ActiveRecord for the attribute values set on the model instance.

record = Post.new(:title => 'Yay', :body => 'This is some insert SQL')

# easiest way to achieve this is by calling protected method
# +arel_attributes_values+ (tested in rails 3.2.13). the alternative
# is to build the entire insert statement using arel >_>
record.class.arel_table.create_insert \
  .tap { |im| im.insert(record.send(:arel_attributes_values, false)) } \
  .to_sql

See the original Gist here.

Update

It's been pointed out that the above code doesn't work in Rails 4.0 and later - the arel_attributes_values method has been removed. This was an old tip, and it abused a protected method after all (although I find the significance of that varies a lot when dealing with Rails).

You can use arel_attributes_with_values_for_create instead:

record = Post.new(:title => 'Yay', :body => 'This is some insert SQL')

record.class.arel_table.create_insert \
  .tap { |im| im.insert(record.send(
                :arel_attributes_with_values_for_create,
                record.attribute_names)) } \
  .to_sql