2015-10-28 20 views
3

我正在運行Ruby 2.1和Mongoid 5.0(無Rails)。如何驗證before_save中的嵌入字段是否發生了變化?

我想跟蹤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

將這兩種方法添加到您的模型和調用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]

相關問題