【问题标题】:Mongoid 3 callbacks: before_upsert vs. before_saveMongoid 3 回调:before_upsert 与 before_save
【发布时间】:2014-10-22 04:22:27
【问题描述】:

对于 Mongoid 3+,是否有各种回调的图表/描述? http://mongoid.org/en/mongoid/v3/callbacks.html

例如,before_upsertbefore_save 之间有什么区别。 save 不是由insertupdate 调用引起的吗?还是save 也被destroy 调用?

另外,before_xxxaround_xxx 有什么区别?

干杯,

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    使用 before_xxx 代码在动作之前执行,而使用 around_xxx 您可以选择在动作本身之前和之后执行代码。

    例如,假设您想在销毁用户项目(用户 has_many :proyects 和项目所属用户)后更新所有用户财产:

    class ProjectsController < ApplicationController
    
      around_destroy :destroy_belongings
    
      def destroy_belongings
        old_user = self.user
        ...
        # Here the before_destroy ends.
    
        yield # Here the destroy is performed itself.
    
        # Here the after_destroy starts. It's needed to do this operation after destroy the project because, imagine, the update_belongings method calculates something related to the current number of proyects. And a simple after_destroy is not useful as we would have lost the project owner.
    
        old_user.update_belongings
      end
    end
    

    您还可以看到相关答案herehere。此外this other article 可能对你有用。

    【讨论】:

    • 谢谢乔萨尔。如何指示我是要在操作本身之前还是之后执行?
    • 使用 around_xxx 你可以使用 yield 来设置它。我会更新我的答案,因为这里我不能包含新行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多