Ruby on rails Rails选择具有关联条件的对象

Ruby on rails Rails选择具有关联条件的对象,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有作者表,有很多书。课堂用书(书桌)。如何有效地选择至少有一本书的作者。目前我正在使用 @authors=Author.where(:active=>true)。选择{| Author | Author.books.count>0} 它工作正常,但运行了许多查询。如何以更有效的方式执行此操作?您可以使用sql执行此操作: Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id)

我有作者表,有很多书。课堂用书(书桌)。如何有效地选择至少有一本书的作者。目前我正在使用

@authors=Author.where(:active=>true)。选择{| Author | Author.books.count>0}


它工作正常,但运行了许多查询。如何以更有效的方式执行此操作?

您可以使用sql执行此操作:

 Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id) > 0")

您可以使用sql执行此操作:

 Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id) > 0")

您可以使用sql执行此操作:

 Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id) > 0")

您可以使用sql执行此操作:

 Author.where(:active => true).joins(:books).group("author_id HAVING count(books.id) > 0")
更好的方法

更好的方法

更好的方法


更好的方法

感谢它的工作,尽管在我的例子中我不得不将.group(“author.id…”)改为.group(“author\u id…”),语句是:author.where(:active=>true)。joins(:books.group(“author\u id HAVING count(books.id)>0”)感谢它的工作,尽管在我的例子中我不得不将.group(“author.id…”改为.group(“author\u id…”)语句类似于:Author.where(:active=>true).joins(:books).group(“Author.id HAVING count(books.id)>0”)感谢它的工作,不过在我的例子中,我不得不将.group(“Author.id…”)更改为.group(“Author.id…”),语句类似于:Author.where(:active=>true).joins(:books).group(“Author.id HAVING count(books.id)>0”)感谢它的工作,尽管在我的例子中,我不得不将.group(“author.id…”)更改为.group(“author\u id…”),语句如下:author.where(:active=>true).joins(:books).group(“author\u id拥有count(books.id)>0”)