← Blog

Rails 6 adds ActiveRecord::Relation#extract_associated

This blog is part of our Rails 6 series.

Before Rails 6, if we want to extract associated records from an ActiveRecord::Relation, we would use preload and collect.

For example, we want to fetch subscriptions of some users. The query would look as shown below.

Rails 5.2

User.where(blocked: false).preload(:subscriptions).collect(&:subscriptions)

=> # returns collection of subscription records

ActiveRecord::Relation#extract_associated provides a shorthand to achieve same result and is more readable than former.

Rails 6.0.0.beta3

User.where(blocked: false).extract_associated(:subscriptions)

=> # returns the same collection of subscription records

Here's the relevant pull request for this change.

Taha Husain avatar
Written byTaha Husain
Newsletter

Stay up to date with our blogs.

Subscribe to receive an email notification for a new blog post.