对于Mongoid 3+,是否有各种回调的图表/描述? http://mongoid.org/en/mongoid/v3/callbacks.html
例如,before_upsert
与before_save
之间的区别是什么。由save
或insert
电话引起的update
不是吗?或save
也会调用destroy
?
另外,before_xxx
和around_xxx
之间有什么区别?
干杯,
答案 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
您还可以查看相关答案here和here。此外this other article可能对您有用。