beesasoh
beesasoh

Reputation: 2125

Rails selecting objects with conditions on associations

I have Author(authors table) and has_many books. Class Book (books table). How can i select authors that have at-least 1 book effectively. Currently am using.

@authors = Author.where(:active => true).select { |author| author.books.count > 0 }

It is working well but it runs many queries. How can i do it in a more effective way?

Upvotes: 0

Views: 78

Answers (2)

Ahmad Hussain
Ahmad Hussain

Reputation: 2491

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

More better way

Upvotes: 1

apneadiving
apneadiving

Reputation: 115521

You can do it with sql:

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

Upvotes: 2

Related Questions