I don’t believe the above works with great-grandchildren however so I’m
curious about that as well. For example if Book has_many :pages and I
want to know all the pages in a certain library. I know it’s always
possible with multiple database calls but wondering what is the most
efficent way.
You can nest this as much as you like. Just be aware of the slightly
quirky
naming conventions for the table aliases, in case you want to add
conditions
to the child or grandchild tables. Have a look at the Rails doco for
Association.
Of course the models could be designed so that there is a direct
[‘shelves.library_id = ?’, @library.id]
I don’t believe the above works with great-grandchildren however so I’m
curious about that as well. For example if Book has_many :pages and I
want to know all the pages in a certain library. I know it’s always
possible with multiple database calls but wondering what is the most
efficent way.
Thanks!!
This is a classic example of why :through was added to has_many in 1.1 -
see the excellent tutorials at:
Be careful though. As you join more tables together, if you don’t have
enough
indexing on the columns which are being joined then your queries will
really
start to drag as more data is added.
Max hit the fastest solution on it with find() and :include, but at the
end of the day, these are all Ruby enumerables, so you can fall back
onto Ruby operators (albeit at the cost of more SQL queries):