Skip to content

Commit f46a611

Browse files
authored
Allow HABTM to use non-standard table names (#96)
1 parent 3bb01b0 commit f46a611

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

lib/jsonapi_compliable/adapters/active_record_sideloading.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,14 @@ def has_and_belongs_to_many(association_name, scope: nil, resource:, foreign_key
9494
parent_ids = parents.map { |p| p.send(primary_key) }
9595
parent_ids.uniq!
9696
parent_ids.compact!
97+
98+
table_name = parents[0]
99+
.class.reflections[through.to_s].klass.table_name
100+
97101
_scope.call
98102
.joins(through)
99103
.preload(through) # otherwise n+1 as we reference in #assign
100-
.where(through => { fk => parent_ids })
104+
.where(table_name => { fk => parent_ids })
101105
.distinct
102106
end
103107

spec/fixtures/legacy.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@
2020
t.integer :hobby_id
2121
end
2222

23+
# test non-standard table name
24+
create_table :author_hobby do |t|
25+
t.integer :author_id
26+
t.integer :hobby_id
27+
end
28+
2329
create_table :hobbies do |t|
2430
t.string :name
2531
end

spec/integration/rails/finders_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,21 @@ def json
367367
expect(author1_hobbies.size).to eq(2)
368368
expect(author2_hobbies.size).to eq(1)
369369
end
370+
371+
context 'when the table name does not match the association name' do
372+
before do
373+
AuthorHobby.table_name = :author_hobby
374+
end
375+
376+
let!(:other_table_hobby1) { Hobby.create!(name: 'Fishing', authors: [author1]) }
377+
let!(:other_table_hobby2) { Hobby.create!(name: 'Woodworking', authors: [author1, author2]) }
378+
379+
it 'still works' do
380+
get :index, params: { include: 'hobbies' }
381+
expect(ids_for('hobbies'))
382+
.to eq([other_table_hobby1.id, other_table_hobby2.id])
383+
end
384+
end
370385
end
371386

372387
context 'sideloading self-referential' do

0 commit comments

Comments
 (0)