Skip to content

Instantly share code, notes, and snippets.

@hiromi2424
Created June 13, 2023 10:32
Show Gist options
  • Save hiromi2424/d9f8449fa2dcd8f8bdfdae38be334099 to your computer and use it in GitHub Desktop.
Save hiromi2424/d9f8449fa2dcd8f8bdfdae38be334099 to your computer and use it in GitHub Desktop.
Bulk Updatable
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