Created
June 13, 2023 10:32
-
-
Save hiromi2424/d9f8449fa2dcd8f8bdfdae38be334099 to your computer and use it in GitHub Desktop.
Bulk Updatable
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 | |
extend ActiveSupport::Concern | |
class_methods do | |
def bulk_update(attributes) | |
return true if attributes.empty? | |
attrs = attributes.map { |attribute| attribute.to_h.symbolize_keys } | |
fields = attrs.first.keys.map(&:to_sym) - [:id] | |
sql = "UPDATE `#{table_name}` SET\n" | |
sql << fields.map do |field| | |
value_def = attrs.map do |attribute| | |
"WHEN #{connection.quote(attribute[:id])} THEN #{connection.quote(attribute[field])}" | |
end.join("\n") | |
"`#{table_name}`.`#{field}` = CASE `#{table_name}`.`id`\n#{value_def}\nEND" | |
end.join(",\n") | |
sql << "\nWHERE `#{table_name}`.`id` IN (#{attrs.pluck(:id).join(',')})" | |
transaction do | |
connection.execute(sql) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment