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