Arnaud
Arnaud

Reputation: 17737

Rails 3.2: how to find all parents from a collection of children

Given a collection of "Books", what is the best way to find all "Authors" (no duplicate) ?

So let's say we have a classic association:

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end

The way I do it right now is this:

@books = Book.where("some condition")
@authors = Author.where(:id => @books.map(&:author_id))

Is there any better way to do it ?

Upvotes: 4

Views: 1205

Answers (2)

charlysisto
charlysisto

Reputation: 3700

Here's a way :

@books = Book.where("some condition").includes(:author)
@authors = @books.map(&:author).compact.uniq

Explanation :

  • include will eager load authors so you don't get dreaded O(n) db calls each time a book wants its author...
  • uniq to remove the duplicate authors (you might want to use inverse_of option in that case not sure)

Upvotes: 2

Ch4rAss
Ch4rAss

Reputation: 754

@books.each.collect(&:author)

or just simply:

@books.collect(&:author)

You can read more about collect here

Upvotes: 0

Related Questions