Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're misreading the docs slightly. <code>some_firm.client.new</code> is creating a new <code>Client</code> object from the clients collection, and so it can automatically set the <code>firm_id</code> to <code>some_firm.id</code>, whereas the docs are calling <code>Client.new</code> which has no knowledge of any Firm's id at all, so it needs the <code>firm_id</code> passed to it.</p> <p>The only difference between <code>some_firm.clients.new</code> and <code>some_firm.clients.build</code> seems to be that <code>build</code> also adds the newly-created client to the <code>clients</code> collection:</p> <pre><code>henrym:~/testapp$ rails c Loading development environment (Rails 3.0.4) r:001 &gt; (some_firm = Firm.new).save # Create and save a new Firm #=&gt; true r:002 &gt; some_firm.clients # No clients yet #=&gt; [] r:003 &gt; some_firm.clients.new # Create a new client #=&gt; #&lt;Client id: nil, firm_id: 1, created_at: nil, updated_at: nil&gt; r:004 &gt; some_firm.clients # Still no clients #=&gt; [] r:005 &gt; some_firm.clients.build # Create a new client with build #=&gt; #&lt;Client id: nil, firm_id: 1, created_at: nil, updated_at: nil&gt; r:006 &gt; some_firm.clients # New client is added to clients #=&gt; [#&lt;Client id: nil, firm_id: 1, created_at: nil, updated_at: nil&gt;] r:007 &gt; some_firm.save #=&gt; true r:008 &gt; some_firm.clients # Saving firm also saves the attached client #=&gt; [#&lt;Client id: 1, firm_id: 1, created_at: "2011-02-11 00:18:47", updated_at: "2011-02-11 00:18:47"&gt;] </code></pre> <p>If you're creating an object through an association, <code>build</code> should be preferred over <code>new</code> as build keeps your in-memory object, <code>some_firm</code> (in this case) in a consistent state even before any objects have been saved to the database.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload