Take the 2-minute tour ×

I have a Customer and Invoice Model. A customer has many invoices and an invoice belongs_to a customer.

class Customer < ActiveRecord::Base
 attr_accessible :billing_address, :customer_currency, :email, :first_name, :last_name,    :mobile, :name, :payment_terms, :phase_type, :pays_vat
 validates_presence_of :first_name, :last_name, :mobile, :billing_address, :payment_terms,  :phase_type, :customer_currency

has_many :invoices

validates :email, 
        :presence => true,
        :uniqueness => true, 
        :email_format => true

validates :name, :mobile, :presence => true, :uniqueness => true

Invoice Model is

class Invoice < ActiveRecord::Base
belongs_to :customer
attr_accessible :approved_by, :due_date, :invoice_date, :terms, :customer_id, :customer

validates :invoice_date, presence: true
validates :due_date, presence: true
validates :customer, presence: true

I am trying to create an index page that lists all the invoices in the system and this will invoice showing a customer Name to whom the invoice belongs. How can i retrieve that and clearly depict it in my model and view?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

I think you've already created customer and invoice controllers and views (if not do it by generate scaffold). Then list invoices in views\invoices\index.html.erb:

<% @invoices.each do |invoice| %>
    <td><%= invoice.num %></td>
    <td><%= invoice.customer.first_name %></td>
<% end %>

Of course, you should declare @invoices in controllers/invoices_controller.rb

def index
  @invoices = Invoice.includes(:customer).all
share|improve this answer
You should probably use Invoice.includes(:customer).all to avoid additional queries while iterating over the invoices. –  Jiří Pospíšil Dec 28 '12 at 20:02
No, if associations are correct it will work as I've shown. –  alex Dec 28 '12 at 20:09
It sure will, but if there are 10 invoices, you will have to make 11 sql queries - get all of the invoices and 1 for each invoice (fetching customer's first_name). If you use the includes method, you have just 2 queries to make. –  Jiří Pospíšil Dec 28 '12 at 20:13
Good notice, thank you. But it will generate the query with in where condition, which is not very quick. Did you make any experiments that says that 'includes' method always better? –  alex Dec 28 '12 at 20:29
I wouldn't worry about IN's performance. The main point is that without the includes call, the number of sql queries would grow with the number of invoices (N+1). With includes, you would still have just 2. –  Jiří Pospíšil Dec 28 '12 at 20:38
show 4 more comments

Your Answer


