Skip to content

Commit f52396a

Browse files
authored
Merge pull request #39 from willsoto/fix/many-to-many
Fix duplicate results when serializing many-to-many relationships
2 parents 4d46476 + 8a67a1f commit f52396a

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

lib/jsonapi_compliable/adapters/active_record_sideloading.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ def has_and_belongs_to_many(association_name, scope: nil, resource:, foreign_key
7676
parent_ids = parents.map { |p| p.send(primary_key) }
7777
parent_ids.uniq!
7878
parent_ids.compact!
79-
_scope.call.joins(through).where(through => { fk => parent_ids })
79+
_scope.call.joins(through).where(through => { fk => parent_ids }).distinct
8080
end
8181

8282
assign do |parents, children|

spec/integration/rails/finders_spec.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def index
122122
let!(:state) { State.create!(name: 'Maine') }
123123
let!(:bio) { Bio.create!(author: author1, picture: 'imgur', description: 'author bio') }
124124
let!(:hobby1) { Hobby.create!(name: 'Fishing', authors: [author1]) }
125-
let!(:hobby2) { Hobby.create!(name: 'Woodworking', authors: [author1]) }
125+
let!(:hobby2) { Hobby.create!(name: 'Woodworking', authors: [author1, author2]) }
126126
let(:house) { House.new(name: 'Cozy', state: state) }
127127
let(:condo) { Condo.new(name: 'Modern', state: state) }
128128
let(:genre) { Genre.create!(name: 'Horror') }
@@ -271,6 +271,19 @@ def json
271271
expect(hobby).to_not have_key('description')
272272
expect(hobby).to_not have_key('reason')
273273
end
274+
275+
it 'does not duplicate results' do
276+
get :index, params: { include: 'hobbies' }
277+
author1_relationships = json['data'][0]['relationships']
278+
author2_relationships = json['data'][1]['relationships']
279+
280+
author1_hobbies = author1_relationships['hobbies']['data']
281+
author2_hobbies = author2_relationships['hobbies']['data']
282+
283+
expect(json_includes('hobbies').size).to eq(2)
284+
expect(author1_hobbies.size).to eq(2)
285+
expect(author2_hobbies.size).to eq(1)
286+
end
274287
end
275288

276289
context 'sideloading self-referential' do

0 commit comments

Comments
 (0)