diff --git a/lib/jsonapi_compliable/adapters/active_record_sideloading.rb b/lib/jsonapi_compliable/adapters/active_record_sideloading.rb index ef23708..169e4b2 100644 --- a/lib/jsonapi_compliable/adapters/active_record_sideloading.rb +++ b/lib/jsonapi_compliable/adapters/active_record_sideloading.rb @@ -94,10 +94,14 @@ 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! + + table_name = parents[0] + .class.reflections[through.to_s].klass.table_name + _scope.call .joins(through) .preload(through) # otherwise n+1 as we reference in #assign - .where(through => { fk => parent_ids }) + .where(table_name => { fk => parent_ids }) .distinct end diff --git a/spec/fixtures/legacy.rb b/spec/fixtures/legacy.rb index e6fdad8..32d2203 100644 --- a/spec/fixtures/legacy.rb +++ b/spec/fixtures/legacy.rb @@ -20,6 +20,12 @@ t.integer :hobby_id end + # test non-standard table name + create_table :author_hobby do |t| + t.integer :author_id + t.integer :hobby_id + end + create_table :hobbies do |t| t.string :name end diff --git a/spec/integration/rails/finders_spec.rb b/spec/integration/rails/finders_spec.rb index e4eebde..9479712 100644 --- a/spec/integration/rails/finders_spec.rb +++ b/spec/integration/rails/finders_spec.rb @@ -367,6 +367,21 @@ def json expect(author1_hobbies.size).to eq(2) expect(author2_hobbies.size).to eq(1) end + + context 'when the table name does not match the association name' do + before do + AuthorHobby.table_name = :author_hobby + end + + let!(:other_table_hobby1) { Hobby.create!(name: 'Fishing', authors: [author1]) } + let!(:other_table_hobby2) { Hobby.create!(name: 'Woodworking', authors: [author1, author2]) } + + it 'still works' do + get :index, params: { include: 'hobbies' } + expect(ids_for('hobbies')) + .to eq([other_table_hobby1.id, other_table_hobby2.id]) + end + end end context 'sideloading self-referential' do