Skip to content

Commit 2a84cdc

Browse files
Ross-Hunterlgebhardt
authored andcommitted
Alters build_joins sql for has_one relationships
The existing tests are passing because they seem to all use a self- referential `has_one` relationship. If the foreign_key is on a different table, however, the queries will fail. So if it the relationship is a has_one, we need to alter the query to look for the foreign-key on the related table.
1 parent 38757c6 commit 2a84cdc

2 files changed

Lines changed: 12 additions & 4 deletions

File tree

lib/jsonapi/active_relation_resource_finder.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,12 @@ def _build_joins(associations)
423423
joins = []
424424

425425
associations.inject do |prev, current|
426-
joins << "LEFT JOIN #{current.table_name} AS #{current.name}_sorting ON #{current.name}_sorting.id = #{prev.table_name}.#{current.foreign_key}"
426+
if current.has_one?
427+
joins << "LEFT JOIN #{current.table_name} AS #{current.name}_sorting ON #{current.name}_sorting.#{current.foreign_key} = #{prev.table_name}.id"
428+
else
429+
joins << "LEFT JOIN #{current.table_name} AS #{current.name}_sorting ON #{current.name}_sorting.id = #{prev.table_name}.#{current.foreign_key}"
430+
end
431+
427432
current
428433
end
429434
joins.join("\n")

test/unit/resource/resource_test.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -360,12 +360,15 @@ def test_lookup_association_chain
360360
end
361361

362362
def test_build_joins
363-
model_names = %w(person posts parent_post author)
363+
model_names = %w(person posts parent_post author author_detail)
364364
associations = PostResource._lookup_association_chain(model_names)
365365
result = PostResource.send(:_build_joins, associations)
366366

367-
assert_equal "LEFT JOIN posts AS parent_post_sorting ON parent_post_sorting.id = posts.parent_post_id
368-
LEFT JOIN people AS author_sorting ON author_sorting.id = posts.author_id", result
367+
sql = "LEFT JOIN posts AS parent_post_sorting ON parent_post_sorting.parent_post_id = posts.id
368+
LEFT JOIN people AS author_sorting ON author_sorting.id = posts.author_id
369+
LEFT JOIN author_details AS author_detail_sorting ON author_detail_sorting.person_id = people.id"
370+
371+
assert_equal sql, result
369372
end
370373

371374
# ToDo: Implement relationship pagination

0 commit comments

Comments
 (0)