我发布了
an article on disabling ActiveModel callbacks,但我不完全确定这是做这样的事情最漂亮的方式.
Mongoid :: Timestamps添加一个更新updated_at字段的保存前回调.假设在某些情况下我不希望这样,我禁用这样的回调:
class User
# I'm using Mongoid, but this should work for anything based on
# ActiveModel.
include Mongoid::Document
include Mongoid::Timestamps
def sneaky_update(attributes)
User.skip_callback(:save, :before, :set_updated_at)
User.update_attributes(attributes)
User.set_callback(:save, :before, :set_updated_at)
end
end
调用skip_callback后跟set_callback再次设置删除的回调是一个坏主意吗?你会怎么做? 🙂
最佳答案 这个怎么样?
module Mongoid
module Timestamps
attr_accessor :skip_updated_at
def set_updated_at_new
unless self.skip_updated_at
set_updated_at_org
end
end
alias set_updated_at_org set_updated_at
alias set_updated_at set_updated_at_new
end
end
class User
# I'm using Mongoid, but this should work for anything based on
# ActiveModel.
include Mongoid::Document
include Mongoid::Timestamps
def sneaky_update(attributes)
self.skip_updated_at = true
User.update_attributes(attributes)
self.skip_updated_at = false
end
end