Display data from more than one table

Hi guys !

I'm a RoR newbye and need to display the content of more than one table
in a view. Let's say I have a Invoices table with a relationship to a
Customers table. I'd like to display on a single page every invoice
informations, including the customer name.

How would I achieve this using ActiveRecord ? My Invoice model is only
able to retrieve data from the Invoices table and my Customer model is
only able to retrieve data from me Customers table.

Thanks by advance,

Eric.

Eric Morand wrote:

Hi guys !

I'm a RoR newbye and need to display the content of more than one table
in a view. Let's say I have a Invoices table with a relationship to a
Customers table. I'd like to display on a single page every invoice
informations, including the customer name.

How would I achieve this using ActiveRecord ? My Invoice model is only
able to retrieve data from the Invoices table and my Customer model is
only able to retrieve data from me Customers table.

Thanks by advance,

Eric.

if your invoices have a customer_id, then

in Invoices model define:
belongs_to :customers

in Customers model:
has_many :invoices

then in the controller:
@invoices + Invoice.find(:all)

in the view:
<% @invoices.each do |invoice %>
<%= invoice.customer.name %> ... plus more invoice data ...
<% end %>

the relevant point is to define the associations like has_many &
belongs_to, which gives you this nice syntax of @invoice.customer...

if your invoices have a customer_id, then

in Invoices model define:
belongs_to :customers

in Customers model:
has_many :invoices

then in the controller:
@invoices + Invoice.find(:all)

in the view:
<% @invoices.each do |invoice %>
<%= invoice.customer.name %> ... plus more invoice data ...
<% end %>

the relevant point is to define the associations like has_many &
belongs_to, which gives you this nice syntax of @invoice.customer...

What ? It is THAT simple ?

I say WOW !

Thanks for the help, it works like a charm !

Eric.

In the situation described you may want to improve the query:

@customer = Customer.find(params[:customer_id], :include=>:invoices)
@invoices = @customer.invoices

That will save you a db roundtrip, often the most taxing part of the
app.