Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fixed issue with nested embedded one's not getting _id set properly.
Test thanks to bhbryant.
  • Loading branch information
jnunemaker committed Dec 27, 2010
1 parent 2a8cf93 commit 8a282c9
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 11 deletions.
Expand Up @@ -16,6 +16,7 @@ def replace(doc)
else
@target = klass.load(doc)
end
@target.default_id_value if @target && @target.id.nil?
assign_references(@target)
loaded
@target
Expand Down
2 changes: 1 addition & 1 deletion lib/mongo_mapper/plugins/clone.rb
Expand Up @@ -6,7 +6,7 @@ module InstanceMethods
def initialize_copy(other)
@_new = true
@_destroyed = false
default_id_value({})
default_id_value
associations.each do |name, association|
instance_variable_set(association.ivar, nil)
end
Expand Down
16 changes: 7 additions & 9 deletions lib/mongo_mapper/plugins/keys.rb
Expand Up @@ -258,6 +258,13 @@ def embedded_keys
keys.values.select { |key| key.embeddable? }
end

def default_id_value(attrs={})
id_provided = !attrs.nil? && attrs.keys.map { |k| k.to_s }.detect { |k| k == 'id' || k == '_id' }
if !id_provided && self.class.can_default_id?
write_key :_id, BSON::ObjectId.new
end
end

private
def load_from_database(attrs)
return if attrs.blank?
Expand All @@ -270,15 +277,6 @@ def load_from_database(attrs)
end
end

def default_id_value(attrs)
unless attrs.nil?
id_provided = attrs.keys.map { |k| k.to_s }.detect { |k| k == 'id' || k == '_id' }
if !id_provided && self.class.can_default_id?
write_key :_id, BSON::ObjectId.new
end
end
end

def ensure_key_exists(name)
self.class.key(name) unless respond_to?("#{name}=")
end
Expand Down
21 changes: 20 additions & 1 deletion test/functional/associations/test_one_embedded_proxy.rb
Expand Up @@ -48,7 +48,7 @@ def setup
should "not have problem loading root document if embedded one is nil" do
@post_class.one :author, :class => @author_class
post = @post_class.create

lambda {
@post_class.find(post.id)
}.should_not raise_error
Expand Down Expand Up @@ -78,4 +78,23 @@ def setup
post.author?.should be_true
end

should "initialize id for nested embedded document created from hash" do
@address_class = EDoc('Address') do
key :city, String
key :state, String
end
@author_class.one(:address, :class => @address_class)
@post_class.one(:author, :class => @author_class)

post = @post_class.create(:title => 'Post Title', :author => {
:name => 'Frank',
:address => {
:city => 'Boston',
:state => 'MA'
}
})

post.author.address.id.should_not be_nil
end

end

0 comments on commit 8a282c9

Please sign in to comment.