Sha256: 2ce1e90f312385b4dd4028bc6251e5dfcedaafa34ddeeb587019932b682148cb

Contents?: true

Size: 1.85 KB

Versions: 8

Compression:

Stored size: 1.85 KB

Contents

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

      # 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, target = nil)
        @options = options
        @target = target || options.klass.find(foreign_key)
        extends(options)
      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, target = nil)
          foreign_key = document.send(options.foreign_key)
          foreign_key.blank? ? nil : new(document, foreign_key, options, target)
        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:
        #
        # target: The target(parent) object
        # document: The +Document+ to update.
        # options: The association +Options+
        #
        # Example:
        #
        # <tt>BelongsToRelated.update(person, game, options)</tt>
        def update(target, document, options)
          document.send("#{options.foreign_key}=", target ? target.id : nil)
          instantiate(document, options, target)
        end
      end

    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
mongoid-pre-2.0.0.beta1 lib/mongoid/associations/belongs_to_related.rb
mongoid-2.0.0.alpha lib/mongoid/associations/belongs_to_related.rb
mongoid-1.2.14 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.2.13 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.2.12 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.2.11 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.2.10 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.2.9 lib/mongoid/associations/belongs_to_related.rb