Sha256: 4e4c53f40f5738ea7a9edd2887bf671165e35313a6e806a2edaeae4e262ee994

Contents?: true

Size: 1.89 KB

Versions: 9

Compression:

Stored size: 1.89 KB

Contents

# encoding: utf-8
module Mongoid #:nodoc:
  module Associations #:nodoc:
    # Represents a relational association to a "parent" object.
    class BelongsToRelated < 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

9 entries across 9 versions & 4 rubygems

Version Path
mongoid-1.9.5 lib/mongoid/associations/belongs_to_related.rb
mongoid-with-auth-1.9.4 lib/mongoid/associations/belongs_to_related.rb
mongoid-rails2-1.9.4 lib/mongoid/associations/belongs_to_related.rb
mongoid-rails2-1.9.3 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.9.2 lib/mongoid/associations/belongs_to_related.rb
sskirby-mongoid-1.9.1 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.9.1 lib/mongoid/associations/belongs_to_related.rb
mongoid-2.0.0.beta.5 lib/mongoid/associations/belongs_to_related.rb
mongoid-1.9.0 lib/mongoid/associations/belongs_to_related.rb