Skip to content

Commit

Permalink
Attempt to fix dowcasting when the document is persisted.
Browse files Browse the repository at this point in the history
  • Loading branch information
lucassus authored and durran committed Nov 10, 2012
1 parent f21de65 commit 8e482fc
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/mongoid/document.rb
Expand Up @@ -217,8 +217,14 @@ def becomes(klass)
unless klass.include?(Mongoid::Document)
raise ArgumentError, "A class which includes Mongoid::Document is expected"
end
became = klass.new(as_document.__deep_copy__)
became.id = id

if changed?
became = klass.new(as_document.__deep_copy__)
became.id = id
else
became = klass.instantiate(as_document.__deep_copy__)
end

became.instance_variable_set(:@changed_attributes, changed_attributes)
became.instance_variable_set(:@errors, errors)
became.instance_variable_set(:@new_record, new_record?)
Expand Down
27 changes: 27 additions & 0 deletions spec/mongoid/document_spec.rb
Expand Up @@ -997,6 +997,33 @@ class Manager < Person
obj.level.should eq(1)
end
end

context "downcasting when the document is persisted" do

let(:obj) do
Person.create(title: 'Sir')
end

let(:became) do
obj.becomes(Manager)
end

context "when downcasted document is saved" do
before { became.save }

it "keeps the type" do
became.should be_an_instance_of(Manager)
end

it "can by queried by the parent class" do
Person.find(became.id).should be_an_instance_of(Manager)
end

it "can by queried by the main class" do
Manager.find(became.id).should be_an_instance_of(Manager)
end
end
end
end

context "when marshalling the document" do
Expand Down

0 comments on commit 8e482fc

Please sign in to comment.