-
Notifications
You must be signed in to change notification settings - Fork 21.8k
Add ActiveRecord::Relation#extract_associated
for extracting associated record
#35784
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
Conversation
…ated records from a relation
@@ -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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea!
🤔 what about |
Load associated is the same as preload. The important part here is that the records returned are those of the association, not of the relation. Extract is the word for taking something like that.
… On Mar 28, 2019, at 16:41, Josef Šimánek ***@***.***> wrote:
🤔 what about load_associated?
—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub, or mute the thread.
|
I'm just trying to find out something similar in current method names since I understand this as a |
As it is, I feel I actually think the current behavior can be quite confusing. As the doc states, account.memberships.extract_associated(:user)
# => Returns collection of User records You could easily expect the following to return a “collection of Comment records”: category.posts.extract_associated(:comments) …but you’d be wrong, as this will instead return a “collection of Comment collections”. |
Add `ActiveRecord::Relation#extract_associated` for extracting associated record rails/rails#35784
It's sometimes more convenient to access a certain set of records by going through a scoped relation and its associations. It's easy enough to do this today using #preload and #collect, but it's repetitive and not descriptive of the intent.
This is where
#extract_associated
comes in. Like so:Which is short-hand for and describing the intent of: