给定一个“书籍”集合,找到所有“作者”(没有副本)的最佳方法是什么?
假设我们有一个经典的联想:

class Author < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :author
end

我现在的做法是:
@books = Book.where("some condition")
@authors = Author.where(:id => @books.map(&:author_id))

有更好的办法吗?

最佳答案

有个办法:

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

说明:
include会急切地加载作者,这样你就不会害怕每当一本书需要它的作者时o(n)db调用……
uniq删除重复的作者(在这种情况下,可能需要使用inverse\u of选项,但不确定)

10-05 20:32
查看更多