【问题标题】:How to verify if an embedded field changed on before_save?如何验证嵌入字段是否在 before_save 上更改?
【发布时间】:2015-10-28 14:51:05
【问题描述】:

我正在运行 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 之前,我想检查是否有其他方法...

【问题讨论】:

    标签: ruby mongodb mongoid


    【解决方案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]

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 2015-05-29
      • 2022-06-15
      • 2011-06-19
      • 2016-07-05
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      相关资源
      最近更新 更多