title: How do I initialize attributes when I instantiate objects in Rails?
body: <p><code>Clients</code> have many <code>Invoices</code>. Invoices have a <code>number</code> attribute that I want to initialize by incrementing the client's previous invoice number.</p>
  
  <p>For example:</p>
  
  <pre><code>@client = Client.find(1)
  @client.last_invoice_number
  &gt; 14
  @invoice = @client.invoices.build
  @invoice.number
  &gt; 15
  </code></pre>
  
  <p>I want to get this functionality into my <code>Invoice</code> model, but I'm not sure how to. Here's what I'm imagining the code to be like:</p>
  
  <pre><code>class Invoice &lt; ActiveRecord::Base
    ...
    def initialize(attributes = {})
      client = Client.find(attributes[:client_id])
      attributes[:number] = client.last_invoice_number + 1
      client.update_attributes(:last_invoice_number =&gt; client.last_invoice_number + 1)
    end
  end
  </code></pre>
  
  <p>However, <code>attributes[:client_id]</code> <em>isn't</em> set when I call <code>@client.invoices.build</code>.</p>
  
  <p>How and when is the invoice's <code>client_id</code> initialized, and when can I use it to initialize the invoice's <code>number</code>? Can I get this logic into the model, or will I have to put it in the controller?</p>