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.

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.

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

AndyV wrote:

On Mar 17, 6:20 am, Thorsten M. <rails-mailing-l…@andreas-
s.net> wrote:

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

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.

Thanks, that’s even better !

On Mar 17, 6:20 am, Thorsten M. <rails-mailing-l…@andreas-
s.net> wrote:

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

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs