Skip to content

Instantly share code, notes, and snippets.

@mockdeep
Created October 29, 2015 17:13
Show Gist options
  • Save mockdeep/f72e379554fe8cb03321 to your computer and use it in GitHub Desktop.
Save mockdeep/f72e379554fe8cb03321 to your computer and use it in GitHub Desktop.
module to add ActiveRecord bulk update functionality for postgres
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