Skip to content

Instantly share code, notes, and snippets.

@tmaier
Forked from fadhlirahim/dirty_associations.rb
Created October 18, 2025 10:16
Show Gist options
  • Save tmaier/4d57f78f328cd71778711f22d3721a5c to your computer and use it in GitHub Desktop.
Save tmaier/4d57f78f328cd71778711f22d3721a5c to your computer and use it in GitHub Desktop.
Awesome simple solution for Rails ActiveRecord dirty tracking associations
# Credit Brandon Weiss of http://anti-pattern.com/dirty-associations-with-activerecord
# app/models/dirty_associations.rb
module DirtyAssociations
attr_accessor :dirty
attr_accessor :_record_changes
def make_dirty(record)
self.dirty = true
self._record_changes = record
end
def changed?
dirty || super
end
end
# app/models/lolrus.rb
class Lolrus
include DirtyAssociations
has_many :buckets,
:after_add => :make_dirty,
:after_remove => :make_dirty
end
# Usage
lol = Lolrus.create!
lol.buckets << Bucket.new
lol.changed?
# => true
lol._record_changes
# => #<Bucket# ... >
lol._record_changes.changed?
# => true
lol._record_changes.changes?
# for example ...
# => {[attr] => [old_value, new_value]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment