Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating Trackable::association_hash to write through parent. #34

Merged
merged 2 commits into from May 1, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 8 additions & 8 deletions lib/mongoid/history/trackable.rb
Expand Up @@ -133,18 +133,18 @@ def traverse_association_chain(node=self)
end

def association_hash(node=self)
# get all reflections of embedded_in association metadata
# and find the first association that matches _parent.
if node._parent
meta = node.reflect_on_all_associations(:embedded_in).find do |meta|
node._parent == node.send(meta.key)
end

inverse = node._parent.reflect_on_association(meta.inverse) if meta
# We prefer to look up associations through the parent record because
# we're assured, through the object creation, it'll exist. Whereas we're not guarenteed
# the child to parent (embedded_in, belongs_to) relation will be defined
if node._parent
meta = _parent.relations.values.select do |relation|
relation.class_name == node.class.to_s
end.first
end

# if root node has no meta, and should use class name instead
name = meta ? meta.inverse.to_s : node.class.name
name = meta ? meta.key.to_s : node.class.name

{ 'name' => name, 'id' => node.id}
end
Expand Down
10 changes: 10 additions & 0 deletions spec/integration/integration_spec.rb
Expand Up @@ -382,6 +382,16 @@ class Tag
@post.tags.count.should == 1
@post.history_tracks.last.action.should == "destroy"
end

it "should write relationship name for association_chain hiearchy instead of class name when using _destroy macro" do
update_hash = {"tags_attributes" => { "1234" => { "id" => @tag_foo.id, "_destroy" => "1"} } }
@post.update_attributes(update_hash)

# historically this would have evaluated to 'Tags' and an error would be thrown
# on any call that walked up the association_chain, e.g. 'trackable'
@tag_foo.history_tracks.last.association_chain.last["name"].should == "tags"
lambda{ @tag_foo.history_tracks.last.trackable }.should_not raise_error
end
end

describe "non-embedded" do
Expand Down