对于 Mongoid 3+,是否有各种回调的图表/描述? http://mongoid.org/en/mongoid/v3/callbacks.html
例如,
before_upsert
与 before_save
之间有什么区别。 save
不是由 insert
或 update
调用引起的吗?还是 save
也被 destroy
调用?
还有,
before_xxx
和around_xxx
有什么区别?
使用 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