Last active
May 19, 2024 11:08
-
-
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
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
# 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 |
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
# 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) |
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
# 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 |
Thanks! I will mention that too!
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
Hey @erados :)
Yeah sure you can use it :)
Side note, @choncou is the original author of this.