-
-
Save ches/759788 to your computer and use it in GitHub Desktop.
bubble down callbacks to embedded associations with mongoid
This file contains 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
# encoding: utf-8 | |
module Mongoid #:nodoc: | |
module Associations #:nodoc: | |
module EmbeddedCallbacks | |
# bubble callbacks to embedded associations | |
def run_callbacks(kind, *args, &block) | |
# now bubble callbacks down | |
self.associations.each_pair do |name, meta| | |
if meta.association == Mongoid::Associations::EmbedsMany | |
self.send(name).each { |doc| doc.send(:run_callbacks, kind, *args, &block) } | |
elsif meta.association == Mongoid::Associations::EmbedsOne | |
self.send(name).send(:run_callbacks, kind, *args, &block) | |
end | |
end | |
super(kind, *args, &block) # defer to parent | |
end | |
end | |
end | |
end |
This file contains 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
class Photo | |
include Mongoid::Document | |
include Mongoid::Timestamps | |
mount_uploader :image, ImageFileUploader | |
embedded_in :some_model, :inverse_of => :photos | |
validates_presence_of :image | |
end |
This file contains 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
class SomeModel | |
include Mongoid::Document | |
include Mongoid::Associations::EmbeddedCallbacks | |
include Mongoid::Timestamps | |
embeds_many :photos | |
end |
You're getting multiple inserts on a sporadic basis because each run_callbacks
call will trigger the block, which contains a persistence operation. (If you call it in a loop, watch out!) I ran into the same issue.
I submitted a pull request that resolves this problem. If it is still a blocker for you, please try out my patch and provide feedback!
For the record I'm now using @paulrosania's patch with success, thanks Paul! Here's hoping it's merged soon.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just noticed the code I posted above don't work that well, it will result in three inserts in some cases. Haven't tracked down the exact cause, don't know enough about how callbacks work yet. Manually doing: