Skip to content

Instantly share code, notes, and snippets.

@jwliechty
Created March 18, 2015 18:25
Show Gist options
  • Save jwliechty/eb7c94657bc6d6bf79f5 to your computer and use it in GitHub Desktop.
Save jwliechty/eb7c94657bc6d6bf79f5 to your computer and use it in GitHub Desktop.
Update parent timestamps when embedded mongoid docs modified
module TouchParentsOnModify
def update(attributes={})
touch_parents
super attributes
end
def save(options={})
touch_parents
super options
end
def destroy(options={})
touch_parents
super options
end
def touch(field=nil)
touch_parents
super field
end
private
def touch_parents
parent = _parent
while parent do
parent.touch if respond_to? :updated_at=
parent = parent._parent
end
end
end
# Some mongoid documents using the module
class MyDoc
include Mongoid::Document
include Mongoid::Timestamps
field :name, default: 'my_name'
embeds_many :my_embedded_docs
end
class MyEmbeddedDoc
include Mongoid::Document
include Mongoid::Timestamps
prepend TouchParentsOnModify #NOTE: prepend the module, NOT include
field :name, default: 'embedded'
embeds_many :my_deep_embedded_docs
embedded_in :my_doc
end
class MyDeepEmbeddedDoc
include Mongoid::Document
include Mongoid::Timestamps
prepend TouchParentsOnModify
field :name, default: 'deep embedded'
embedded_in :my_embedded_doc
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment