Mongoid 3回调:before_upsert与before_save

时间:2014-08-28 10:27:46

标签: ruby-on-rails mongoid

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

例如,before_upsertbefore_save之间的区别是什么。由saveinsert电话引起的update不是吗?或save也会调用destroy

另外,before_xxxaround_xxx之间有什么区别?

干杯,

1 个答案:

答案 0 :(得分:0)

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

例如,假设您想在销毁用户项目后更新所有用户所有物(User has_many:proyects和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

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