我正在运行 Ruby 2.1 和 Mongoid 5.0(没有 Rails)。
我想在 before_save
回调中跟踪嵌入字段是否已更改。
我可以使用 document.attribute_changed?
或 document.changed
方法来检查普通字段,但不知何故这些不适用于关系(embed_one、has_one 等) ).
有没有办法在保存文档之前检测到这些更改?
我的模型是这样的
class Company
include Mongoid::Document
include Mongoid::Attributes::Dynamic
field :name, type: String
#...
embeds_one :address, class_name: 'Address', inverse_of: :address
#...
before_save :activate_flags
def activate_flags
if self.changes.include? 'address'
#self.changes never includes "address"
end
if self.address_changed?
#This throws an exception
end
end
我如何保存文档的一个例子是:
#...
company.address = AddressUtilities.parse address
company.save
#After this, the callback is triggered, but self.changes is empty...
#...
我已经阅读了文档并谷歌了一番,但我找不到解决方案?
我找到了 this gem , 但它很旧并且不适用于较新版本的 Mongoid。在考虑尝试修复/拉取请求 gem 之前,我想检查是否有另一种方法...
最佳答案
将这两个方法添加到您的模型并调用 get_embedded_document_changes
应该会为您提供一个散列,其中包含对其所有嵌入文档的更改:
def get_embedded_document_changes
data = {}
relations.each do |name, relation|
next unless [:embeds_one, :embeds_many].include? relation.macro.to_sym
# only if changes are present
child = send(name.to_sym)
next unless child
next if child.previous_changes.empty?
child_data = get_previous_changes_for_model(child)
data[name] = child_data
end
data
end
def get_previous_changes_for_model(model)
data = {}
model.previous_changes.each do |key, change|
data[key] = {:from => change[0], :to => change[1]}
end
data
end
关于ruby - 如何验证嵌入字段是否在 before_save 上发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394317/