Sha256: e208be5a7de21d2b63fd4cd84ec565af486cf3b54bc1dee3827ad7c4021899b6

Contents?: true

Size: 1023 Bytes

Versions: 9

Compression:

Stored size: 1023 Bytes

Contents

module Spyke
  module Associations
    class HasMany < Association
      def initialize(*args)
        super
        @options.reverse_merge!(uri: "/#{parent.class.model_name.plural}/:#{foreign_key}/#{klass.model_name.plural}/:id")
        @params[foreign_key] = parent.id
      end

      def load
        self
      end

      def assign_nested_attributes(collection)
        collection = collection.values if collection.is_a?(Hash)

        collection.each do |attributes|
          if existing = find_existing_attributes(attributes.with_indifferent_access[:id])
            existing.merge!(attributes)
          else
            build(attributes)
          end
        end
      end

      private

        def find_existing_attributes(id)
          embedded_attributes.to_a.find { |attr| attr[:id] && attr[:id].to_s == id.to_s }
        end

        def add_to_parent(record)
          parent.attributes[name] ||= []
          parent.attributes[name] << record.attributes
          record
        end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
spyke-1.3.0 lib/spyke/associations/has_many.rb
spyke-1.2.1 lib/spyke/associations/has_many.rb
spyke-1.2.0 lib/spyke/associations/has_many.rb
spyke-1.1.2 lib/spyke/associations/has_many.rb
spyke-1.1.1 lib/spyke/associations/has_many.rb
spyke-1.1.0 lib/spyke/associations/has_many.rb
spyke-1.0.2 lib/spyke/associations/has_many.rb
spyke-1.0.1 lib/spyke/associations/has_many.rb
spyke-1.0.0 lib/spyke/associations/has_many.rb