Reputation: 17737
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
Reputation: 3700
Here's a way :
@books = Book.where("some condition").includes(:author)
@authors = @books.map(&:author).compact.uniq
Explanation :
Upvotes: 2