Rails 3.2: How to Find All Parents from a Kids Collection

Given the Book collection, what's the best way to find all the "authors" (no duplicates)?

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'm doing it right now is:

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

Is there a better way to do this?

+4
source share
2 answers

Here is the way:

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

Explanation:

  • include will be impatient to authors of loading, therefore you will not be afraid of calls of O (n) db every time the book wants its author ...
  • uniq to remove duplicate authors (you can use the inverse_of option in this case not surely)
+1
source
 @books.each.collect(&:author) 

or simply:

 @books.collect(&:author) 

More about assembly here

0
source

All Articles