Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Created March 15, 2024 18:00
Show Gist options
  • Save hopsoft/b5f3d45711df7b95ebfdfb3d565bada3 to your computer and use it in GitHub Desktop.
Save hopsoft/b5f3d45711df7b95ebfdfb3d565bada3 to your computer and use it in GitHub Desktop.
Get the SQL for an insert statement from ActiveRecord
# Builds an SQL insert query for a given record
#
# @param record [ActiveRecord::Base] Record used to build the SQL insert query
# @return [String] SQL insert query
def build_insert_query(record)
columns = record.class.columns.reject { |col| col.name == record.class.primary_key }
values = columns.map { |col| record[col.name] }
insert_manager = Arel::InsertManager.new
insert_manager.into(record.class.arel_table)
insert_manager.insert(columns.zip(values)).to_sql
end
user = User.new(first_name: "John", last_name: "Doe")
build_insert_sql(user) # => SQL instert query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment