Tuesday 15 March 2011

mongoid4 - How to ignore an unknown subclass with single collection inheritance in Mongoid? -



mongoid4 - How to ignore an unknown subclass with single collection inheritance in Mongoid? -

the default inheritance method mongoid creating single collection subclasses. instance:

class user include mongoid::document end class admin < user end class invitee < user end

internally, mongoid adds _type field each document class name, used automatically map each instance right class.

the problem is, if have document in collection unknown _type value, exception:

nameerror: uninitialized constant unknownclass

this can happen if create new subclass of user, in illustration above, , migration creates new instance of new subclass. until restart servers, every query collection (like user.all.to_a). there safe way avoid error?

the solution came rescuing nameerror exception , querying known subclasses:

class user def self.some_query(params) self.where(params).to_a rescue nameerror => e rails.logger.error "unknown subclass: #{e.message}" subtypes = self.descendants.map(&:to_s) self.where(params.merge(:_type.in => subtypes)).to_a end end

mongoid mongoid4

No comments:

Post a Comment