Ruby on rails 是否可以在RubyonRails中为已更改的mongoid嵌入文档字段创建回调?
是否有一种方法仅在嵌入式文档字段更改时运行回调 当前,以下命令仅在普通字段发生更改时才对其运行回调:Ruby on rails 是否可以在RubyonRails中为已更改的mongoid嵌入文档字段创建回调?,ruby-on-rails,mongoid,Ruby On Rails,Mongoid,是否有一种方法仅在嵌入式文档字段更改时运行回调 当前,以下命令仅在普通字段发生更改时才对其运行回调: class user field :email, type: String embeds_many :connections, cascade_callbacks: true before_save :run_callback, :if => :email_changed? before_save :run_connection_callback, :if => :c
class user
field :email, type: String
embeds_many :connections, cascade_callbacks: true
before_save :run_callback, :if => :email_changed?
before_save :run_connection_callback, :if => :connections_changed? # DOES NOT WORK
end
Mongoid不会为您定义方法
connections\u 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\u changed
仅在保存文档时设置。回调以这样的方式进行级联:首先调用保存前的连接回调,然后调用保存前的用户回调,这允许上述代码在此用例中工作。但是,如果您需要在调用save
之前知道是否有任何连接已更改,则需要找到另一种方法。Mongoid不会为您定义方法connections\u 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\u changed
仅在保存文档时设置。回调以这样的方式进行级联:首先调用保存前的连接回调,然后调用保存前的用户回调,这允许上述代码在此用例中工作。但是,如果您需要在调用save
之前知道任何连接是否已更改,则需要找到另一种方法。对于2015年看到此答案的任何人
在Mongoid 4.x中,model.changed?和model.changes与ActiveRecord的同类产品一样存在并表现出来。对于2015年看到这个答案的人来说
在Mongoid 4.x中,model.changed?和model.changes的存在和行为与ActiveRecord的对应项类似。自从Mongoid 4.x(甚至更早)发生更改以来?自从Mongoid 4.x(甚至更早)更改后,是否有可用的更改方法(请参见下面的答案)?并提供更改方法(请参见下面的答案)