ruby - How to reference an embedded document in Mongoid? -
using mongoid, let's have following classes:
class map include mongoid::document embeds_many :locations end class location include mongoid::document field :x_coord, :type => integer field :y_coord, :type => integer embedded_in :map, :inverse_of => :locations end class player include mongoid::document references_one :location end
as can see, i'm trying model simple game world environment map embeds locations, , player references single location current spot.
using approach, i'm getting following error when try reference "location" attribute of player class:
mongoid::errors::documentnotfound: document not found class location id(s) xxxxxxxxxxxxxxxxxxx.
my understanding because location document embedded making difficult reference outside scope of embedding document (the map). makes sense, how model direct reference embedded document?
because maps own collection, need iterate on every map collection searching within location player referenced.
you can't access embedded documents directly. have enter through collection , work way down.
to avoid iterating of maps can store both location reference , map reference in player document. allows chain criteria selects map , location within it. have code method on player class handle this.
def location self.map.locations.find(self.location_id) end
so, similar how answered except still store location_id in player document instead of using coord attribs.
another way put maps, locations, , players in own collections instead of embedding location in map collection. use reference relationships without doing fancy... using hierarchical database likes it's relational database @ point...
Comments
Post a Comment