Skip to content

Instantly share code, notes, and snippets.

@timm-oh
Last active May 19, 2024 11:08
Show Gist options
  • Save timm-oh/9b702a15f61a5dd20d5814b607dc411d to your computer and use it in GitHub Desktop.
Save timm-oh/9b702a15f61a5dd20d5814b607dc411d to your computer and use it in GitHub Desktop.
Rails 5.2.3: Monkey patch update_all and update_columns to always include updated_at
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
# Didn't change #update_column because it uses #update_columns under the hood.
def update_columns(attrs)
new_attrs = attrs.symbolize_keys
new_attrs[:updated_at] ||= Time.current if self.class.column_names.include?('updated_at')
super(new_attrs)
end
end
# config/initializers/core_extentions.rb
Dir[File.expand_path(File.join(File.dirname(File.absolute_path(__FILE__)), 'lib/core_extensions')) + "/**/*.rb"].each do |file|
require file
end
ActiveRecord::Relation.prepend(CoreExtensions::ActiveRecord::CustomUpdateAll)
# lib/core_extensions/active_record/custom_update_all.rb
module CoreExtensions
module ActiveRecord
module CustomUpdateAll
def update_all(updates)
if updates.is_a?(Hash) && !updates.delete(:skip_touch)
# Didn't do updates[:updated_at] ||= Time.current
# because it changes the original updates hash
super({ updated_at: Time.current, **updates.symbolize_keys })
else
super(updates)
end
end
end
end
end
@sdhull
Copy link

sdhull commented Feb 27, 2024

Thanks for this nice share 😄

You can make requiring core extensions a bit simpler, like this:

Dir[Rails.root.join("lib/core_extensions/**/*.rb")].sort.each do |file|
  require file
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment