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 Genre: has_many Subgenres Subgenres: belongs_to genre has_many books_subgenres has_many books, through books_subgenres Book: 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? Thanks!
on 19.08.2008 18:16
on 19.08.2008 18:27
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
on 19.08.2008 20:02
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. e.g. Genre.first.books.english But its a start! Thanks!
on 20.08.2008 01:54
What about has_many :cs :through => :a?
on 20.08.2008 10:09
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