ruby - 如何验证嵌入字段是否在 before_save 上发生了变化?

标签 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。在考虑尝试修复/拉取请求 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

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

关于ruby - 如何验证嵌入字段是否在 before_save 上发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394317/

相关文章:

Ruby 正则表达式多次重复捕获

mongodb - Mongo - 如何在单个查询中更新具有不同值的多个文档?

Node.js 和 Mongodb

ruby-on-rails - Mongoid:嵌入文档在父级构造时自动初始化

ruby-on-rails - Mongoid 日期 (DateTime) 字段未正确解析以存储到数据库中

ruby-on-rails - 第一个 Rails 项目 : Rake Problem

reactjs - 无法启动reactJS服务器|错误: "rbenv: yarn: command not found"

ruby - 如何在不先安装 Ruby GEM 的情况下开发它?

Python + MongoDB,如何动态选择DB Collection

mongodb - 如何检查 Mongoid 的连接