Sha256: d7cd1d99986c3b10c8bb8ea04b2b3b29c0be7a2a921b4ae35dc771ec9ee66bd2

Contents?: true

Size: 1.25 KB

Versions: 2

Compression:

Stored size: 1.25 KB

Contents

module MongoMapper
  module Associations
    class ManyProxy < ArrayProxy
      delegate :klass, :to => :@association
      
      def find(*args)
        options = args.extract_options!
        klass.find(*args << scoped_options(options))
      end
      
      def paginate(options)
        klass.paginate(scoped_options(options))
      end
      
      def all(options={})
        find(:all, scoped_options(options))
      end
      
      def first(options={})
        find(:first, scoped_options(options))
      end
      
      def last(options={})
        find(:last, scoped_options(options))
      end
      
      def replace(docs)
        if load_target
          @target.map(&:destroy)
        end

        docs.each do |doc|
          @owner.save if @owner.new?
          doc.send(:write_attribute, self.foreign_key, @owner.id)
          doc.save
        end
        
        reload_target
      end

      protected
        def scoped_options(options)
          options.dup.deep_merge({:conditions => {self.foreign_key => @owner.id}})
        end
        
        def find_target
          find(:all)
        end

        def foreign_key
          @association.options[:foreign_key] || @owner.class.name.underscore.gsub("/", "_") + "_id"
        end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
jnunemaker-mongomapper-0.3.0 lib/mongomapper/associations/many_proxy.rb
jnunemaker-mongomapper-0.3.1 lib/mongomapper/associations/many_proxy.rb