Topic: Find all grandchildren

:customer has_many :locations
:location has_many :work_orders

Is there a Rails idiom to find all :work_orders for a given :customer?

@customer.locations.work_orders doesn't seem to work sad

I thought about how mothers feed their babies with tiny little spoons and forks, so I wondered what do Chinese mothers use. Toothpicks?

Re: Find all grandchildren

Try setting:

class Customer < ActiveRecord::Base
  has_many :locations
  has_many :work_orders, :through => :locations
end

Then you can access it with @customer.work_orders

Railscasts - Free Ruby on Rails Screencasts

Re: Find all grandchildren

Oh cool, I thought that has_many :through was only useful as a replacement for habtm. You learn something new every day smile

I thought about how mothers feed their babies with tiny little spoons and forks, so I wondered what do Chinese mothers use. Toothpicks?

Re: Find all grandchildren

I have a similar situation in an online ticketing app for a movie theatre.

my model is as follows:

Cinema's have many movies
movies have many actors
actors can be in many movies

class cinema < ActiveRecord::Base
  has_many :movies
  has_many :actors, :through => :movies
end

In my Cinema's show view I want to list the movies showing for a particular day and then for each movie all the actors in each movie


I am struggling to work out how to code this in my view..
I was trying to loop through the actors with the following
<% for actor in @cinema.movies.actor %>

any suggestions?

Re: Find all grandchildren

You need two loops here, one for the movies and one for the actors of each movie, so you don't even need the has_many :through association in cinema since you are just looping through the actors of a given movie.

<% for movie in @cinema.movies %>
  <h2><%=h movie.name %></h2>
  <ul>
  <% for actor in movie.actors %>
    <li><%=h actor.name %></li>
  <% end %>
  </ul>
<% end %>

Actually you will need one more loop for the days, but that depends on how the date is stored in the movies.

Last edited by ryanb (2006-10-08 16:22:47)

Railscasts - Free Ruby on Rails Screencasts

Re: Find all grandchildren

Thanks ryan.. works perfectly..