Skip to content

Instantly share code, notes, and snippets.

@balakirevs
Forked from fadhlirahim/dirty_associations.rb
Created December 15, 2019 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balakirevs/a824b283f8b33e6843b3d2c76b502619 to your computer and use it in GitHub Desktop.
Save balakirevs/a824b283f8b33e6843b3d2c76b502619 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