Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add association validation errors on unsuccessful sidepost #148

Open
seocahill opened this issue Jan 22, 2019 · 0 comments
Open

Add association validation errors on unsuccessful sidepost #148

seocahill opened this issue Jan 22, 2019 · 0 comments

Comments

@seocahill
Copy link
Contributor

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
@seocahill seocahill changed the title Add association validation errors on unsucessful sidepost Add association validation errors on unsuccessful sidepost Jan 28, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant