Created
January 22, 2016 11:59
-
-
Save mahemoff/40dd8e36492083c28386 to your computer and use it in GitHub Desktop.
simple active record bulk-updater with different values in a single column Raw
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
class ActiveRecord::Base | |
def self.bulk_update(column, values_by_id) | |
ids = values_by_id.keys.join(',') | |
query = [] | |
query << ["UPDATE #{self.table_name} SET #{column}=case id"] | |
query << values_by_id.map { |id, count| | |
"WHEN #{id} THEN #{count}" | |
} | |
query << "END" | |
query << "WHERE id IN (#{ids})" | |
query = query.join("\n") | |
self.connection.execute query | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment