Simple parent child view

I have 2 tables (clients and orders). I have create models for them
both and the relevant belongs_to has_many declarations.

I’ve created a controller which has the following code:

def list_orders
@all_clients = Client.find(:all)
@all_orders = Order.find(:all)
end

I’ve created a view which has the following code:
<% for client in @all_clients %>
<%=h(client.name) %>
<% for order in @all_orders %>
<%=h(order.detail) %>
<% end %>
<% end %>

Now what i want to see is a list of clients with their individual
order details listed underneath. Instead of course im seeing each
client with every client order detail listed underneath. The
problem I have is that I dont know how to pass the current client id
to the order loop to get a true parent/child view.

I’m missing something really basic here, but its stumping me at the
moment.

Here is what I would do. I’m new to this, so perhaps there is a
better way.

I would take out the Order.find statement.

Instead, take advantage of the methods Rails gives you for free when
you set up the belongs_to and has_many relationship.

For example, you could use the following inside your main loop:

for order in client.orders

instead of

for order in @all_orders

class Client
has_many :orders
end
def list_orders
@all_clients = Client.find(:all, :include=>[:orders])
end
for client in all_clients
<%=client.name%>
for order in client.orders
<%=order.id%>
end
end

Fantastic! Thank you both. For those who want a full listing:

TABLES:

DROP TABLE IF EXISTS demo_development.clients;
CREATE TABLE demo_development.clients (
id int(10) unsigned NOT NULL auto_increment,
name varchar(45) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS demo_development.orders;
CREATE TABLE demo_development.orders (
id int(10) unsigned NOT NULL auto_increment,
client_id int(10) unsigned NOT NULL,
description varchar(45) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

*Create new rails project…

MODELS:
class Client < ActiveRecord::Base
has_many :orders
end

class Order < ActiveRecord::Base
belongs_to :clients
end

CONTROLLER:
class InvoiceController < ApplicationController
def list_orders
@all_clients = Client.find(:all, :include => [:orders])
end
end

VIEW:(list_orders.rhtml)
<% for client in @all_clients %>
<%=client.name%>
<% for order in client.orders %>
<%=order.description%>
<% end %>
<% end %>