Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ActiveRecord::Relation#extract_associated for extracting associated record #35784

Merged
merged 4 commits into from Mar 29, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,3 +1,12 @@
* Add `ActiveRecord::Relation#extract_associated` for extracting associated records from a relation.

```
account.memberships.extract_associated(:user)
# => Returns collection of User records
```

*DHH*

* Add `ActiveRecord::Relation#annotate` for adding SQL comments to its queries.

For example:
Expand Down
13 changes: 13 additions & 0 deletions activerecord/lib/active_record/relation/query_methods.rb
Expand Up @@ -154,6 +154,19 @@ def preload!(*args) # :nodoc:
self
end

# Extracts a named +association+ from the relation. The named association is first preloaded,
# then the individual association records are collected from the relation. Like so:
#
# account.memberships.extract_associated(:user)
# # => Returns collection of User records
#
# This is short-hand for:
#
# account.memberships.preload(:user).collect(&:user)
def extract_associated(association)
preload(association).collect(&association)
end

# Use to indicate that the given +table_names+ are referenced by an SQL string,
# and should therefore be JOINed in any query rather than loaded separately.
# This method only works in conjunction with #includes.
Expand Down
5 changes: 5 additions & 0 deletions activerecord/test/cases/relations_test.rb
Expand Up @@ -602,6 +602,11 @@ def test_preload_applies_to_all_chained_preloaded_scopes
end
end

def test_extracted_association
authors = Post.all.extract_associated(:author)
assert_equal Post.all.collect(&:author), authors
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we should wrap the extract in an assert_queries 1, such that we test the preload query optimization.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea!

end

def test_find_with_included_associations
assert_queries(2) do
posts = Post.includes(:comments).order("posts.id")
Expand Down