Skip to content

Commit adf09db

Browse files
committed
CPK: Fix specifying single record in association
Single records in CPK contexts will take on an array to represent their identifier. This was problematic because if only a single record is passed, it's hard to distinguish the behaviour between a list of multiple primary keys or a list representing a single primary key. As such, it's helpful to always wrap the result of the single ID in an array, so as to disambiguate the cases and create consistency in the shape of the id structure.
1 parent 795d524 commit adf09db

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

activerecord/lib/active_record/relation/predicate_builder/association_query_value.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def ids
2626
when Array
2727
value.map { |v| convert_to_id(v) }
2828
else
29-
convert_to_id(value)
29+
[convert_to_id(value)]
3030
end
3131
end
3232

activerecord/test/cases/associations_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,15 @@ def test_querying_by_whole_associated_records_using_query_constraints
166166
assert_equal(expected_posts.map(&:id).sort, blog_posts.map(&:id).sort)
167167
end
168168

169+
def test_querying_by_single_associated_record_works_using_query_constraints
170+
comments = [sharded_comments(:great_comment_blog_post_one), sharded_comments(:great_comment_blog_post_two)]
171+
172+
blog_posts = Sharded::BlogPost.where(comments: comments.last).to_a
173+
174+
expected_posts = [sharded_blog_posts(:great_post_blog_two)]
175+
assert_equal(expected_posts.map(&:id).sort, blog_posts.map(&:id).sort)
176+
end
177+
169178
def test_has_many_association_with_composite_foreign_key_loads_records
170179
blog_post = sharded_blog_posts(:great_post_blog_one)
171180

0 commit comments

Comments
 (0)