'Is there a Rails way to get all associated objects of an ActiveRecord::Relation?
Let's suppose we've 2 models:
class Author < ApplicationRecord
has_many :books
end
class Book < ApplicationRecord
belongs_to :author
end
and we want to get a list of all Books - on a page where we're already querying all Authors along with their associated books as follow:
@authors = Author.all.includes(:books)
We could do it using Ruby as so:
@authors.map(&:books) # returns an ActiveRecord::Associations::CollectionProxy
But is there a Rails' way of doing it that would return an ActiveRecord::Relation ?
Solution 1:[1]
extract_associated(association)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 recordsThis is short-hand for:
account.memberships.preload(:user).collect(&:user)
https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-extract_associated
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | max |
