Custom constructor for nested EmbeddedDocuments

27 views
Skip to first unread message

Drew Cimino

unread,
Jan 27, 2012, 4:42:50 PM1/27/12
to MongoMapper
So the main Document I'm using has 3 EmbeddedDocuments all nested
inside each other (one-to-many). Since I don't know exactly how many
of the embedded documents will get constructed, I decided the easiest
way to do build the Document would be to factor out the building into
the constructor for each model, rather than serializing all the data
on the fly and using a giant pile of nested build() spaghetti code to
build a model.

When I try to build a new nested model, like so:

class Resource
include MongoMapper::Document

MongoMapper.database = "db"

key :name, String

many :things

def initialize(data)
@name = data[:name]
self.populate_things(data[:things])
end

def populate_things(new_things)
new_things.each do |new_thing|
@things.push(Thing.new(new_thing))
end
end

end


I get an error, telling me that there's no method 'push' for nil, and
I have found absolutely nothing online telling me how to access the
array of many 'things'.

What lets me do this, or if there's a better way to go about what I'm
trying to do, please enlighten me. Thanks very much.

John Nunemaker

unread,
Feb 4, 2012, 6:08:54 PM2/4/12
to mongo...@googlegroups.com
There is no method push for nil because you are using an instance variable @things, instead of the association, things. Use things.push and your error will may go away. 

You definitely don't want to override initialize the way you are. That will probably make MM not work at all because then the MM initialize will never be called.

That said, not sure that your implementation makes sense to me. Seems like an example using made up names rather than the real thing so it is hard to know what to suggest.



--
You received this message because you are subscribed to the Google
Groups "MongoMapper" group.
For more options, visit this group at
http://groups.google.com/group/mongomapper?hl=en?hl=en

Reply all
Reply to author
Forward
0 new messages