Mongoid 3 回调:before_upsert 与 before_save

问题描述 投票:0回答:1

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

例如,

before_upsert
before_save
之间有什么区别。
save
不是由
insert
update
调用引起的吗?还是
save
也被
destroy
调用?

还有,

before_xxx
around_xxx
有什么区别?

ruby-on-rails mongoid
1个回答
0
投票

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

例如,假设您想在销毁用户项目后更新所有用户所有物(User has_many :proyects and Project belongs_to User):

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

您还可以在这里这里看到相关答案。此外另一篇文章可能对你有用。

© www.soinside.com 2019 - 2024. All rights reserved.