phil
August 19, 2008, 6:16pm
1
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!
phil
August 19, 2008, 8:02pm
2
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!
phil
August 19, 2008, 6:27pm
3
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
phil
August 20, 2008, 10:09am
4
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
phil
August 20, 2008, 1:54am
5
What about has_many :cs :through => :a?