Last Updated: February 25, 2016
· 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 = => '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)) } \

See the original Gist here.


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 = => 'Yay', :body => 'This is some insert SQL')

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