From 8a67a1f08834276cfbc2f020265f98516c14bb87 Mon Sep 17 00:00:00 2001 From: Will Date: Fri, 21 Jul 2017 13:41:43 -0400 Subject: [PATCH] Fix duplicate results when serializing many-to-many relationships Signed-off-by: Will --- .../adapters/active_record_sideloading.rb | 2 +- spec/integration/rails/finders_spec.rb | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/jsonapi_compliable/adapters/active_record_sideloading.rb b/lib/jsonapi_compliable/adapters/active_record_sideloading.rb index b2ffbf5..1a6725e 100644 --- a/lib/jsonapi_compliable/adapters/active_record_sideloading.rb +++ b/lib/jsonapi_compliable/adapters/active_record_sideloading.rb @@ -76,7 +76,7 @@ def has_and_belongs_to_many(association_name, scope: nil, resource:, foreign_key parent_ids = parents.map { |p| p.send(primary_key) } parent_ids.uniq! parent_ids.compact! - _scope.call.joins(through).where(through => { fk => parent_ids }) + _scope.call.joins(through).where(through => { fk => parent_ids }).distinct end assign do |parents, children| diff --git a/spec/integration/rails/finders_spec.rb b/spec/integration/rails/finders_spec.rb index b4d5326..196f3bc 100644 --- a/spec/integration/rails/finders_spec.rb +++ b/spec/integration/rails/finders_spec.rb @@ -122,7 +122,7 @@ def index let!(:state) { State.create!(name: 'Maine') } let!(:bio) { Bio.create!(author: author1, picture: 'imgur', description: 'author bio') } let!(:hobby1) { Hobby.create!(name: 'Fishing', authors: [author1]) } - let!(:hobby2) { Hobby.create!(name: 'Woodworking', authors: [author1]) } + let!(:hobby2) { Hobby.create!(name: 'Woodworking', authors: [author1, author2]) } let(:house) { House.new(name: 'Cozy', state: state) } let(:condo) { Condo.new(name: 'Modern', state: state) } let(:genre) { Genre.create!(name: 'Horror') } @@ -271,6 +271,19 @@ def json expect(hobby).to_not have_key('description') expect(hobby).to_not have_key('reason') end + + it 'does not duplicate results' do + get :index, params: { include: 'hobbies' } + author1_relationships = json['data'][0]['relationships'] + author2_relationships = json['data'][1]['relationships'] + + author1_hobbies = author1_relationships['hobbies']['data'] + author2_hobbies = author2_relationships['hobbies']['data'] + + expect(json_includes('hobbies').size).to eq(2) + expect(author1_hobbies.size).to eq(2) + expect(author2_hobbies.size).to eq(1) + end end context 'sideloading self-referential' do