jsonapi-suite / jsonapi_compliable

MIT License
20 stars 35 forks source link

Add association validation errors on unsuccessful sidepost #148

Open seocahill opened 5 years ago

seocahill commented 5 years ago

To recreate:

results in:

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

expect:

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