Skip to content

Commit

Permalink
Eager evaluate relation in composite case
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
paarthmadan committed Apr 19, 2023
1 parent adf09db commit 45da2cf
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
Expand Up @@ -10,7 +10,10 @@ def initialize(associated_table, value)

def queries
if associated_table.join_foreign_key.is_a?(Array)
ids.map { |ids_set| associated_table.join_foreign_key.zip(ids_set).to_h }
id_list = ids
id_list = id_list.pluck(primary_key) if id_list.is_a?(Relation)

id_list.map { |ids_set| associated_table.join_foreign_key.zip(ids_set).to_h }
else
[ associated_table.join_foreign_key => ids ]
end
Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/associations_test.rb
Expand Up @@ -175,6 +175,14 @@ def test_querying_by_single_associated_record_works_using_query_constraints
assert_equal(expected_posts.map(&:id).sort, blog_posts.map(&:id).sort)
end

def test_querying_by_relation_with_composite_key
expected_posts = [sharded_blog_posts(:great_post_blog_one), sharded_blog_posts(:great_post_blog_two)]

blog_posts = Sharded::BlogPost.where(comments: Sharded::Comment.where(body: "I really enjoyed the post!")).to_a

assert_equal(expected_posts.map(&:id).sort, blog_posts.map(&:id).sort)
end

def test_has_many_association_with_composite_foreign_key_loads_records
blog_post = sharded_blog_posts(:great_post_blog_one)

Expand Down

0 comments on commit 45da2cf

Please sign in to comment.