A -> B -> C... A has_many C's?

Hi... I am sure this is a newb question but, here goes.

I have three models:

Genre - can have many subgenres
Subgenre - only one genre, can have many books
Book - can belong to many subgenres

has_many Subgenres

belongs_to genre
has_many books_subgenres
has_many books, through books_subgenres

has_many books_subgenres
has_many subgenres, through books_subgenres

I have a joining model called Books_Subgenre

Right now I have no problem getting the book's subgenres, or the
subgenres books or the genres subgenres

But I want to get the genres books. How do I do that? Or indeed the
books genres?


Since Genre has many Subgenres, and a Subgenre has many Books:

genre = Genre.find(id)

# returns an array of the genre's subgenres
subs = genre.subgenres

# returns an array of all the books in genre
genre_books = subs.inject([]) { |array, sub| array += sub.books }

Someone might have an easier way to do this but this ought to
accomplish your purpose. You'd probably want to define this as a
method in the Genre model so you can do something like:

genre = Genre.find(id)
books = genre.books

Thank Matt... that works, though I have to admit I was hoping for a
way that would let me use the named_scopes I have definted on Books.


But its a start! Thanks!

What about has_many :cs :through => :a?

Do you mean through b?
If so, that doesn't seem to work as the relationship between b and c
is through a joining model