Mongoid 不会connections_changed?
为您定义方法,但您可以通过使用虚拟字段来自己定义它,User
以跟踪嵌入式连接何时更改。那是:
class User
# define reader/writer methods for @connections_changed
attr_accessor :connections_changed
def connections_changed?
self.connections_changed
end
# the connections are no longer considered changed after the persistence action
after_save { self.connections_changed = false }
before_save :run_connection_callback, :if => :connections_changed?
end
class Connection
embedded_in :user
before_save :tell_user_about_change, :if => :changed?
def tell_user_about_change
user.connections_changed = true
end
end
此方法的一个缺点是user.connections_changed
仅在保存文档时才设置。回调以这样的方式级联,即Connection
before_save
首先调用回调,然后User
before save
调用回调,这允许上述代码适用于此用例。但是,如果您需要在调用之前知道任何连接是否发生了变化,则save
需要找到另一种方法。