Skip to content

Add association validation errors on unsuccessful sidepost #148

@seocahill

Description

@seocahill

To recreate:

  • parent has_one child
  • patch parent with sidepost child method: update and invalid params

results in:

ActiveRecord::RecordNotSaved:Failed to save the new associated child as parent.send("#{association_name}=", child) tries to associate invalid child.

expect:

  • 422 with errors returned

Here's my monkeypatch

module JsonapiCompliable
  module Adapters
    # @see Adapters::Abstract
    class ActiveRecord < Abstract
      # When a has_many relationship, we need to avoid Activerecord implicitly
      # firing a query. Otherwise, simple assignment will do
      # @see Adapters::Abstract#associate
      def associate(parent, child, association_name, association_type)
        if association_type == :has_many
          associate_many(parent, child, association_name)
        elsif association_type == :habtm
          if parent.send(association_name).exists?(child.id)
            associate_many(parent, child, association_name)
          else
            parent.send(association_name) << child
          end
        elsif association_type == :has_one
          if child.valid?
            parent.send("#{association_name}=", child)
          else
            child.errors.full_messages.each do |message|
              parent.errors.add(association_name, message)
            end
          end
        elsif
          child.send("#{association_name}=", parent)
        end
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions