Skip to content

Commit 45da2cf

Browse files
committed
Eager evaluate relation in composite case
Normally, it's valid syntax to pass the predicate builder a mapping from primary key to a record, to an id, or to a relation. With the composite case, there's a limitation on the types of syntax supported. Namely, the only case we support right now is mapping a tuple of columns to a tuple of corresponding values. For now, it's sufficient to extract the ids instead of evaluating the SQL at a later time.
1 parent adf09db commit 45da2cf

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

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

Lines changed: 4 additions & 1 deletion
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

activerecord/test/cases/associations_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,14 @@ def test_querying_by_single_associated_record_works_using_query_constraints
175175
assert_equal(expected_posts.map(&:id).sort, blog_posts.map(&:id).sort)
176176
end
177177

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+
178186
def test_has_many_association_with_composite_foreign_key_loads_records
179187
blog_post = sharded_blog_posts(:great_post_blog_one)
180188

0 commit comments

Comments
 (0)