Created
March 18, 2015 18:25
-
-
Save jwliechty/eb7c94657bc6d6bf79f5 to your computer and use it in GitHub Desktop.
Update parent timestamps when embedded mongoid docs modified
This file contains hidden or 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
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