Created
June 27, 2011 17:17
-
-
Save mxriverlynn/1049304 to your computer and use it in GitHub Desktop.
get changes to mongoid document, including embedded documents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
module Document | |
def changes_with_embedded | |
field_data = get_previous_changes_for_model(self) | |
embedded_data = get_embedded_document_changes(self) | |
unless embedded_data.empty? | |
field_data.merge embedded_data | |
end | |
end | |
private | |
def get_embedded_document_changes(model) | |
data = {} | |
model.relations.each do |name, relation| | |
next unless [:embeds_one, :embeds_many].include? relation.macro.to_sym | |
# only if changes are present | |
child = model.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 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
当 relation 是 embeds_many 时,child 会是一个数组对象,Line 23 会报错