Skip to content

Instantly share code, notes, and snippets.

@digitalplaywright
Created December 29, 2011 18:46
Show Gist options
  • Save digitalplaywright/1535543 to your computer and use it in GitHub Desktop.
Save digitalplaywright/1535543 to your computer and use it in GitHub Desktop.
Mongoid syntax for inverse_of relations
  1. To declare multiple fields using the same embedded model, like e.g:
class Profile
  include Mongoid::Document

  embeds_many :i_am_a,    :class_name => "TagInteraction", :inverse_of => :i_am_a
  embeds_many :i_love_to, :class_name => "TagInteraction", :inverse_of => :i_love_to
end

class Label
  include Mongoid::Document

  embedded_in :profile, :inverse_of => :i_am_a
  embedded_in :profile, :inverse_of => :i_love_to
end

If it was not for a Mongoid bug this could also be expressed using a more concise polymorphic relation.

  1. To declare multiple associations to the same model.
class Profile
  include Mongoid::Document

  has_and_belongs_to_many :administrates, :class_name => "Event", 
                                     :inverse_of => :admins
  has_and_belongs_to_many :attends, :class_name => "Event", 
                                     :inverse_of => :attendees
end

class Event
  include Mongoid::Document

  has_and_belongs_to_many :admins,        :class_name => "Profile",         
                                     :inverse_of => :administrates
  has_and_belongs_to_many :attendees,           :class_name => "Profile", 
                                     :inverse_of => :attends

end

  1. To change the name of an association to something more informative in the context, like e.g:
class Profile
  include Mongoid::Document

  has_many :reviews_of_me, :class_name => "Review"
end

class Review
  include Mongoid::Document

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