我的问题与此How to skip ActiveRecord callbacks?相似,但我不是使用AR,而是使用Mongoid,似乎在当前版本的Mongoid中尚未实现,所以我想知道什么应该是优雅的解决方案来实现它。 (如有必要)。
是的,可以!
Mongoid建立在ActiveModel上,而ActiveModel具有skip_callback function。您可以像这样使用skip_callback
:
# 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)
我正在大型应用程序中顺利使用它。有关更多信息,请参阅Jeff Kreeftmeijer的博客文章:
http://jeffkreeftmeijer.com/2010/disabling-activemodel-callbacks/
使用Mongoid原子操作(设置,取消设置等可能更容易:
https://docs.mongodb.com/mongoid/current/tutorials/mongoid-persistence/#atomic
这些不会触发回调。
编辑:Mongoid 3说他们不触发回调。我看到他们虽然在Mongoid 2中触发了回调。所以YMMV
我最终使用了Brian Armstrong的建议,然后简单地打电话给我
person.set(name:"Robert Pulson")
在我的保存后回调中。
通常,当您要执行更新而不触发大量项目的所有回调时,通常会出现这种情况。可以通过下降到驱动程序来完成:
在'x'字段中用'bar'替换'foo'。
User.all.each do |u|
User.collection.where({ _id: u.id }).update({
"$set" => { :x => u.x.gsub('foo', 'bar')
})
end
我搜索代码。而且没有办法避免在Mongoid中进行回调。在1.9和2.0版本中。
您需要对此进行补丁或功能请求。