title: Default creation of has_one dependency in rails
body: <p>I'd like to understand best practices for creating a dependency of a model in rails. The scenario is simple. The two models are:</p>
  
  <pre><code>class Main &lt; ActiveRecord::Base 
      has_one :dependent
      validates :dependent, presence: true
  end
  
  class Dependent &lt; ActiveRecord::Base 
  end
  </code></pre>
  
  <p>(Note that I want to validate to ensure the dependent always exists)</p>
  
  <p>Whenever a <code>Main</code> object is created I want a <code>Dependent</code> object to be created and "default initialized". I come from a background of C++ hence I view this problem as one of constructing a member variable whose type is some <code>class</code> which has a default constructor.</p>
  
  <p>There are a bunch of ways I can solve this.</p>
  
  <ol>
  <li>Put logic in <code>before_validation</code> to create a <code>Dependent</code>.</li>
  </ol>
  
  <p>This feels very "un-railsy". I wanted to do this in <code>before_create</code> but validations are done before that callback. Doing it in <code>before_validation</code> is ugly as this callback is called both on create <em>and</em> on update, which makes the logic tricky/messy. </p>
  
  <ol start="2">
  <li>Put logic in <code>.new</code></li>
  </ol>
  
  <p>This feels very <em>very</em> "un-railsy" and is probably conceptually wrong. I'd see <code>new</code> as performing <code>ActiveRecord</code> construction which happens before the model is built.</p>
  
  <ol start="3">
  <li>Make the caller do the work</li>
  </ol>
  
  <p>Whenever a <code>Main</code> object is created it must be done via <code>new-save</code> rather than <code>create</code>. The calling code then has to create <code>Dependent</code> itself, albeit with default values, e.g.</p>
  
  <pre><code>Main.new do |m|
      m.dependent = Dependent.create
  end
  </code></pre>
  
  <p>This is annoyingly burdensome on callers and causes a lot of duplicate code. I could pack this into a factory type method but the same problem exists that calling code needs to do some legwork.</p>
  
  <p>Is there a canonical solution to this?</p>