我有作者(作者表)和has_many书。班级书(书籍表)。如何有效地选择至少拥有1本书的作者。目前正在使用。
@authors = Author.where(:active => true).select { |author| author.books.count > 0 }
运行良好,但运行了很多查询。我怎样才能更有效地做到这一点?
答案 0 :(得分:2)
你可以用sql:
来做 Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id) > 0")
答案 1 :(得分:1)
Author.where(:active => true).joins(:books).group(:id).having("count(books.id) > 0")
更好的方式