Skip to content

Instantly share code, notes, and snippets.

@lankz
Created June 6, 2013 03:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lankz/5719044 to your computer and use it in GitHub Desktop.
Save lankz/5719044 to your computer and use it in GitHub Desktop.
record = Post.new(:title => 'Yay', :body => 'This is some insert SQL')
# easiest way to achieve this is by calling protected #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
@formigarafa
Copy link

thanks, and: Or for Rails 4

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.attributes.compact.keys
    ))
  }.to_sql

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment