Some questions about embedding documents

17 views
Skip to first unread message

iain

unread,
May 31, 2010, 8:23:51 AM5/31/10
to MongoModel
Hi,

I'm trying to use embedded documents, and I was wondering if I was
doing it right.

I have these classes:

class Project < MongoModel::Document
property :location, Location
end

class Location < MongoModel::EmbeddedDocument
# more properties
end

It seems to work, but I'm not really sure if this is the right thing
to do. And is there a way to auto-instantiate the Location class? I
have to do this now:

class Project
def initialize(*)
super
self.location = Location.new if location.nil?
end
end

It would be handy (I think) if this wast automatic.

Thanks,
Iain

Sam

unread,
May 31, 2010, 8:30:46 AM5/31/10
to MongoModel
Hi Iain,

You can set a default attribute on the property:

class Project < MongoModel::Document
property :location, Location, :default => lambda { Location.new }
end

Make sure you use a lambda so that you refer to a new Location
instance each time you instantiate the project.

-Sam

iain

unread,
May 31, 2010, 8:57:37 AM5/31/10
to MongoModel
Hi Sam,

Thanks for the quick reply.
Still a bit verbose, if you ask me. Is this intentional?

Cheers, Iain

Sam

unread,
May 31, 2010, 7:31:21 PM5/31/10
to MongoModel
Hi Iain,

I was actually mistaken in my first reply when I said that the lambda
was required. You can actually just do :default => Location.new, and
the Location will be cloned when the Project is instantiated.

class Project < MongoModel::Document
property :location, Location, :default => Location.new
end

The reason MongoModel works this way is for consistency with other
property types. Most property values (e.g. String, Integer, etc) will
default to nil so I wanted to maintain this with embedded documents.
In your app or someone else's, a Project may not require a Location
and hence it would be nil.

Thanks,
Sam
Reply all
Reply to author
Forward
0 new messages