如何验证before_save上是否更改了嵌入字段?

时间:2015-10-28 14:51:06

标签: ruby mongodb mongoid

我正在运行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。我想在考虑尝试修复/拉取请求宝石之前检查是否还有其他方法...

1 个答案:

答案 0 :(得分:-1)

将这两个方法添加到模型中并调用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

[来源:https://gist.github.com/derickbailey/1049304]