Skip to content

Commit d8a8df3

Browse files
authored
Merge pull request rails#47996 from Shopify/pm/cpk-query-by-single-record
Extend query-association interface for composite models
2 parents c978035 + 45da2cf commit d8a8df3

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ def initialize(associated_table, value)
1010

1111
def queries
1212
if associated_table.join_foreign_key.is_a?(Array)
13-
ids.map { |ids_set| associated_table.join_foreign_key.zip(ids_set).to_h }
13+
id_list = ids
14+
id_list = id_list.pluck(primary_key) if id_list.is_a?(Relation)
15+
16+
id_list.map { |ids_set| associated_table.join_foreign_key.zip(ids_set).to_h }
1417
else
1518
[ associated_table.join_foreign_key => ids ]
1619
end
@@ -26,7 +29,7 @@ def ids
2629
when Array
2730
value.map { |v| convert_to_id(v) }
2831
else
29-
convert_to_id(value)
32+
[convert_to_id(value)]
3033
end
3134
end
3235

activerecord/test/cases/associations_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,23 @@ 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+
178+
def test_querying_by_relation_with_composite_key
179+
expected_posts = [sharded_blog_posts(:great_post_blog_one), sharded_blog_posts(:great_post_blog_two)]
180+
181+
blog_posts = Sharded::BlogPost.where(comments: Sharded::Comment.where(body: "I really enjoyed the post!")).to_a
182+
183+
assert_equal(expected_posts.map(&:id).sort, blog_posts.map(&:id).sort)
184+
end
185+
169186
def test_has_many_association_with_composite_foreign_key_loads_records
170187
blog_post = sharded_blog_posts(:great_post_blog_one)
171188

0 commit comments

Comments
 (0)