Permalink
Browse files

Instantiate empty docs when provided nil.

- If embedded documents are somehow persisted as nil in the database, we
  should instantiate them as empty documents client side.

- Fixes #2003.
  • Loading branch information...
durran committed May 12, 2012
1 parent 1dca852 commit 780b43258688c4d4ed93521b4807492531815c06
Showing with 21 additions and 3 deletions.
  1. +3 −0 CHANGELOG.md
  2. +3 −3 lib/mongoid/factory.rb
  3. +15 −0 spec/unit/mongoid/factory_spec.rb
View
@@ -7,6 +7,9 @@ For instructions on upgrading to newer versions, visit
### Resolved Issues
+* \#2003 Don't fail on document generation when an embedded document was
+ stored as nil in the database.
+
* \#1994 `dependent: :delete` only hits the database once now for one to
many and many to many relations instead of once for each document.
View
@@ -15,7 +15,7 @@ module Factory
# @param [ Hash ] optiosn The mass assignment scoping options.
#
# @return [ Document ] The instantiated document.
- def build(klass, attributes = {}, options = {})
+ def build(klass, attributes = nil, options = {})
type = (attributes || {})["_type"]
if type && klass._types.include?(type)
type.constantize.new(attributes, options)
@@ -34,8 +34,8 @@ def build(klass, attributes = {}, options = {})
# @param [ Hash ] attributes The document attributes.
#
# @return [ Document ] The instantiated document.
- def from_db(klass, attributes = {})
- type = attributes["_type"]
+ def from_db(klass, attributes = nil)
+ type = (attributes || {})["_type"]
if type.blank?
klass.instantiate(attributes)
else
@@ -96,6 +96,21 @@
describe ".from_db" do
+ context "when the attributes are nil" do
+
+ let(:document) do
+ described_class.from_db(Address, nil)
+ end
+
+ it "generates based on the provided class" do
+ document.should be_a(Address)
+ end
+
+ it "sets the attributes to empty" do
+ document.attributes.should be_empty
+ end
+ end
+
context "when a type is in the attributes" do
context "when the type is a class" do

0 comments on commit 780b432

Please sign in to comment.