Skip to content

Instantly share code, notes, and snippets.

@zerobearing2
Created September 5, 2010 19:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save zerobearing2/566242 to your computer and use it in GitHub Desktop.
Save zerobearing2/566242 to your computer and use it in GitHub Desktop.
bubble down callbacks to embedded associations with mongoid
# encoding: utf-8
module Mongoid #:nodoc:
module Associations #:nodoc:
module EmbeddedCallbacks
# bubble callbacks to embedded assocaitions
def run_callbacks(*args)
# 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, args)}
elsif meta.association == Mongoid::Associations::EmbedsOne
self.send(name).send(:run_callbacks, args)
end
end
super(args) # defer to parent
end
end
end
end
class Photo
include Mongoid::Document
include Mongoid::Timestamps
mount_uploader :image, ImageFileUploader
embedded_in :some_model, :inverse_of => :photos
validates_presence_of :image
end
class SomeModel
include Mongoid::Document
include Mongoid::Associations::EmbeddedCallbacks
include Mongoid::Timestamps
embeds_many :photos
end
@wprater
Copy link

wprater commented Dec 5, 2010

Thanks.. this is working for me, but do we still need to update the method signature as suggested here:
https://github.com/jnicklas/carrierwave/issues#issue/81/comment/401158

@robobluebird
Copy link

Hey zerobearing2

I know this post is pretty old, but could you tell me where to put the 'embedded_callbacks.rb' file? I am new to rails and I'm not sure where to put files like this.

Thanks!

{Zach}

@wprater
Copy link

wprater commented Aug 23, 2011

Zach,

Just place it where ever your ruby files would get auto-loaded. {root}/lib is a good place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment