Skip to content

Instantly share code, notes, and snippets.

@ryancheung
Created June 22, 2014 17:49
Show Gist options
  • Select an option

  • Save ryancheung/e16bbdc18165a242cb6e to your computer and use it in GitHub Desktop.

Select an option

Save ryancheung/e16bbdc18165a242cb6e to your computer and use it in GitHub Desktop.
Generate insert sql using ActiveRecord(Rails 4)
record = User.new(username: 'ryan', email: 'ryan@hua.li')
record.class.arel_table.create_insert.tap do |im|
im.insert(record.send(:arel_attributes_with_values_for_create, record.attribute_names))
end.to_sql
@matthewhively
Copy link
Copy Markdown

For reference if anyone else stumbles into this

For rails 5.2
I copied this from https://github.com/IFTTT/polo/pull/54/files

def generate_insert_sql_for_model(record)
  values = record.send(:attributes_with_values_for_create, record.class.column_names)
  model = record.class
  substitutes_and_binds = model.send(:_substitute_values, values)

  insert_manager = model.arel_table.create_insert
  insert_manager.insert substitutes_and_binds

  model.connection.unprepared_statement do
    model.connection.to_sql(insert_manager)
  end
end

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