Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何在保存前验证嵌入字段是否已打开?_Ruby_Mongodb_Mongoid - Fatal编程技术网

Ruby 如何在保存前验证嵌入字段是否已打开?

Ruby 如何在保存前验证嵌入字段是否已打开?,ruby,mongodb,mongoid,Ruby,Mongodb,Mongoid,我正在运行Ruby 2.1和Mongoid 5.0(没有Rails) 我想在保存回调之前跟踪,无论嵌入字段是否已更改 我可以使用document.attribute\u changed?或document.changed方法来检查正常字段,但不知何故,这些方法在关系上不起作用(embed\u one、has\u one等) 在保存文档之前,是否有方法检测这些更改 我的模型是这样的 class Company include Mongoid::Document include Mong

我正在运行Ruby 2.1和Mongoid 5.0(没有Rails)

我想在保存回调之前跟踪
,无论嵌入字段是否已更改

我可以使用
document.attribute\u changed?
document.changed
方法来检查正常字段,但不知何故,这些方法在关系上不起作用(embed\u one、has\u 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...
#...
我已经阅读了文档并用谷歌搜索了它,但我找不到解决方案


我发现了,但它很旧,不能与新版本的Mongoid一起使用。在考虑尝试修复/拉取请求gem之前,我想检查是否还有其他方法…

将这两种方法添加到您的模型中,并调用
get\u embedded\u document\u 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
[来源:]