Created
March 15, 2024 18:00
-
-
Save hopsoft/b5f3d45711df7b95ebfdfb3d565bada3 to your computer and use it in GitHub Desktop.
Get the SQL for an insert statement from ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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