Sha256: bd9f80a68af13549efe93afd9bc132bd53106d89f4474566ec102d556d48eb53

Contents?: true

Size: 1.43 KB

Versions: 8

Compression:

Stored size: 1.43 KB

Contents

require 'active_type/nested_attributes/association'

module ActiveType

  module NestedAttributes

    class AssignmentError < StandardError; end

    class NestsOneAssociation < Association

      def assign_attributes(parent, attributes)
        return if attributes.nil?
        attributes = attributes.with_indifferent_access
        return if reject?(parent, attributes)

        assigned_child = assigned_children(parent).first
        destroy = truthy?(attributes.delete(:_destroy)) && @allow_destroy

        if id = attributes.delete(:id)
          assigned_child ||= fetch_child(parent, id)
          if assigned_child
            assigned_child.id = id
            if assigned_child.id == assigned_child.id_was
              assigned_child.attributes = attributes
            else
              raise AssignmentError, "child record '#{@target_name}' did not match id '#{id}'"
            end
            if destroy
              assigned_child.mark_for_destruction
            end
          end
        elsif !destroy
          assigned_child ||= add_child(parent, build_child(parent, {}))
          assigned_child.attributes = attributes
        end
      end


      private

      def add_child(parent, child)
        parent[@target_name] = child
      end

      def assign_children(parent, children)
        parent[@target_name] = children.first
      end

      def derive_class_name
        @target_name.to_s.camelize
      end

    end

  end

end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
active_type-1.3.1 lib/active_type/nested_attributes/nests_one_association.rb
active_type-1.3.0 lib/active_type/nested_attributes/nests_one_association.rb
active_type-1.2.1 lib/active_type/nested_attributes/nests_one_association.rb
active_type-1.2.0 lib/active_type/nested_attributes/nests_one_association.rb
active_type-1.1.1 lib/active_type/nested_attributes/nests_one_association.rb
active_type-1.1.0 lib/active_type/nested_attributes/nests_one_association.rb
active_type-1.0.0 lib/active_type/nested_attributes/nests_one_association.rb
active_type-0.7.5 lib/active_type/nested_attributes/nests_one_association.rb