relations

Relations are associations between one model and another in the domain and in the database. Embedded relations describe documents who are stored inside other documents in the database. Referenced relations describe documents that reference documents in another collection by storing data (usually an id) about the other document in itself.

All relation objects in Mongoid are proxies to the actual document or documents themselves, which provide extra functionality for accessing, replacing, appending and persisting.

commonalities between all relations

attributes

All relations contain a target, which is the proxied document or documents, a base which is the document the relation hangs off, and metadata which provides information about the relation.

class Person
  include Mongoid::Document
  embeds_many :addresses
end

person.addresses = [ address ]
person.addresses.target #=> returns [ address ]
person.addresses.base #=> returns person
person.addresses.metadata #=> returns the metadata

extensions

All relations can have extensions, which provides a way to add application specific functionality to the relation. They are defined by providing a block to the relation definition.

class Person
  include Mongoid::Document
  embeds_many :addresses do
    def find_by_country(country)
      where(country: country).first
    end
    def chinese
      @target.select { |address| address.country == "China"}
    end
  end
end

person.addresses.find_by_country('Mongolia') #=> returns address
person.addresses.chinese #=> returns [ address ]

custom relation names

You can name your relations whatever you like, but if the class cannot be inferred by Mongoid from the name, and neither can the opposite side you'll want to provide the macro with some additional options to tell Mongoid how to hook them up.

class Lush
  include Mongoid::Document
  embeds_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
end

class Drink
  include Mongoid::Document
  embedded_in :alcoholic, class_name: "Lush", inverse_of: :whiskey
end