Created
October 29, 2015 17:13
-
-
Save mockdeep/f72e379554fe8cb03321 to your computer and use it in GitHub Desktop.
module to add ActiveRecord bulk update functionality for postgres
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
module BulkUpdatable | |
def bulk_update(objects, attribute) | |
return unless objects.any? | |
query = build_query_for(objects, attribute) | |
connection.execute(query) | |
end | |
private | |
def build_query_for(objects, attribute) | |
values = objects.map { |object| sanitized_values(object, attribute) } | |
<<-SQL | |
UPDATE #{table_name} | |
SET #{attribute} = tmp_table.#{attribute} | |
FROM (VALUES #{values.join(',')}) AS tmp_table(id, #{attribute}) | |
WHERE #{table_name}.id = tmp_table.id | |
SQL | |
end | |
def sanitized_values(object, attribute) | |
sanitize_sql_array(['(?, ?)', object.id, object.read_attribute(attribute)]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment