Sha256: 58042fa765472d3754f97d9ac5e5eb00222ef42ea09f8ae8be234fc03c28dcf2

Contents?: true

Size: 1.88 KB

Versions: 5

Compression:

Stored size: 1.88 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module Associations #:nodoc:
    class BelongsToRelated #:nodoc:

      delegate :==, :to => :document
      attr_reader :document

      # Initializing a related association only requires looking up the object
      # by its id.
      #
      # Options:
      #
      # document: The +Document+ that contains the relationship.
      # options: The association +Options+.
      def initialize(document, foreign_key, options)
        @document = options.klass.find(foreign_key)
      end

      # Delegate all missing methods over to the +Document+.
      def method_missing(name, *args)
        @document.send(name, *args)
      end

      class << self
        # Instantiate a new +BelongsToRelated+ or return nil if the foreign key is
        # nil. It is preferrable to use this method over the traditional call
        # to new.
        #
        # Options:
        #
        # document: The +Document+ that contains the relationship.
        # options: The association +Options+.
        def instantiate(document, options)
          foreign_key = document.send(options.foreign_key)
          foreign_key.nil? ? nil : new(document, foreign_key, options)
        end

        # Returns the macro used to create the association.
        def macro
          :belongs_to_related
        end

        # Perform an update of the relationship of the parent and child. This
        # will assimilate the child +Document+ into the parent's object graph.
        #
        # Options:
        #
        # related: The related object
        # parent: The parent +Document+ to update.
        # options: The association +Options+
        #
        # Example:
        #
        # <tt>BelongsToRelated.update(game, person, options)</tt>
        def update(related, parent, options)
          parent.send("#{options.foreign_key}=", related.id); related
        end
      end

    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mongoid-0.10.0 lib/mongoid/associations/belongs_to_related.rb
mongoid-0.9.12 lib/mongoid/associations/belongs_to_related.rb
mongoid-0.9.11 lib/mongoid/associations/belongs_to_related.rb
mongoid-0.9.10 lib/mongoid/associations/belongs_to_related.rb
mongoid-0.9.9 lib/mongoid/associations/belongs_to_related.rb