views:

7

answers:

1

2 models Books (has_many: chapters) Chapters (belongs_to: books)

Id like to display a list of books, but only books with chapters.

Here's what I have so far:

@books = Book.find(:all,:include => :chapters)

Problem here is that books is returning books w/o chapters (0 chapters)

when dealing with nested resources like this, how do I say find where count > 0 for chapters?

Right now I'm doing this in the controller, not sure if that's a problem. but i should probably move this to a model?

cheers

A: 

Add this code to Book:

scope :only_with_chapters, includes(:chapters).having('COUNT(chapters.id) > 0').group('books.id')

And to use it just run Book.only_with_chapters

Depends on performance use joins, instead of includes.

Dmitry Polushkin