gpt4 book ai didi

ruby-on-rails - 如何跳过 Mongoid 文档的回调?

转载 作者:数据小太阳 更新时间:2023-10-29 06:31:19 24 4
gpt4 key购买 nike

我的问题与这个类似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/

关于ruby-on-rails - 如何跳过 Mongoid 文档的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3046919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com