Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/jsonapi_compliable/adapters/active_record_sideloading.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 6 additions & 0 deletions spec/fixtures/legacy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions spec/integration/rails/finders_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down