Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip callbacks on Mongoid Documents?

My question is similar to this one How to skip ActiveRecord callbacks? but instead of AR I'm using Mongoid, It seems like that isn't implemented yet in the current version of Mongoid, so I'd like to know what should be an elegant solution to implement it. (if necessary).

like image 837
jpemberthy Avatar asked Jun 15 '10 16:06

jpemberthy


3 Answers

Yes you can!

Mongoid is built on ActiveModel and ActiveModel has a skip_callback function. You can use skip_callback like this:

# skip the callback
MyModelClass.skip_callback(:save, :before, :ensure_foo_is_not_bar)

# rescue any errors to ensure callback is restored afterwords
begin
  my_model_instance.update_attributes :foo => 'bar'
rescue
  puts "Error from 'my_model_instance.update_attributes': #{$!}"
end

# restore the callback for future calls
MyModelClass.set_callback(:save, :before, :ensure_foo_is_not_bar)

I'm using this without a hitch in a big app. For more info, see this blog post by Jeff Kreeftmeijer:

http://jeffkreeftmeijer.com/2010/disabling-activemodel-callbacks/

like image 127
bowsersenior Avatar answered Nov 04 '22 20:11

bowsersenior


It might be easier to use the Mongoid atomic operations (set, unset, etc):

https://docs.mongodb.com/mongoid/current/tutorials/mongoid-persistence/#atomic

These do not fire callbacks.

Edit: Mongoid 3 says they do not fire callbacks. I am seeing them fire callbacks in Mongoid 2 though. So YMMV

like image 26
Brian Armstrong Avatar answered Nov 04 '22 21:11

Brian Armstrong


I ended up using Brian Armstrong's suggestion and simply calling

person.set(name:"Robert Pulson")

in my after save callback.

like image 17
hb922 Avatar answered Nov 04 '22 21:11

hb922