-
-
Save timm-oh/9b702a15f61a5dd20d5814b607dc411d to your computer and use it in GitHub Desktop.
# 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 |
Thank you for sharing your code. ๐
I have a question, Why did you symbolize updates
? Is it necessary ?
@erados It's not necessary. Just generally prefer working with symbols everywhere instead of string keys ๐
Hi @timm-oh .
I hope you're doing well.
I'm reaching out again regarding the article I've been working on for Dev.to, which was inspired by your insightful code.
I'd like to request your permission to reference and discuss your code in the article.
Of course, I'll ensure full credit is given with a direct link to your work.
If you have any concerns or prefer that I don't include it, please let me know, and I'll respect your wishes.
Thanks again for your valuable sharing ๐
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
Just what I have looked for weeks ๐