Skip to content

Instantly share code, notes, and snippets.

@digitalplaywright
Created December 29, 2011 19:21
Show Gist options
  • Save digitalplaywright/1535744 to your computer and use it in GitHub Desktop.
Save digitalplaywright/1535744 to your computer and use it in GitHub Desktop.
Updated examples with the suggested MongoMapper :inverse_of syntax

We use inverse_of in three ways in Mongoid. I've attempted to translate the way we currently use inverse_of in Mongoid to the @bkeepers inverse_of syntax:

  1. Update: use :class_name to specify the class and :inverse_of to specify the inverse association if the :class_name and :inverse_of association can not be inferred from the association definition.

To declare multiple associations to the same model.

I believe :inverse_of and :class_name can be inferred in the trivial case where the field name equals the class or collection name.

class Profile
  include MongoMapper::Document

  many :administrates,  :class_name => "Event", :inverse_of => :admins
  many :reservations,   :class_name => "Event", :inverse_of => :guests
end

class Event
  include MongoMapper::Document

  many :admins,   :class_name => Profile, :inverse_of => :administrates
  many :guests,   :class_name => Profile, :inverse_of => :reservations
end

The array storing the variables could be "#{self.model_name}_#{association_field_name}_ids".

  1. Update: use :class_name to specify the class and :inverse_of to specify the inverse association if needed.

To change the name of an association to something more informative in the context, like e.g:

This becomes the same as number 2 in the many-to-many association. For the many-to-one association it can be:

class Profile
  include MongoMapper::Document

  many :reviews_of_me,   :class_name => "Review", :inverse_of => :review_of
end

class Review
  include MongoMapper::Document

  belongs_to :review_of, :class_name => Profile, :inverse_of => :reviews_of_me
end

  1. Update: :inverse_of not needed

To declare multiple fields using the same embedded model, like e.g:

class Profile
  include MongoMapper::Document

  many :i_am_a,     :class_name => 'TagInteraction'
  many :i_love_to,  :class_name => 'TagInteraction'
end

class TagInteraction
  include MongoMapper::EmbeddedDocument
  
end

This could apply to anything that has different uses of the same concept, like e.g labels and reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment