title: Rails: How can I access the parent model of a new record's nested associations?
body: <p>Suppose we have the standard Post &amp; Comment models, with Post having <code>accepts_nested_attributes_for :commments</code> and <code>:autosave =&gt; true</code> set.</p>
  
  <p>We can create a new post together with some new comments, e.g.:</p>
  
  <pre><code>@post = Post.new :subject =&gt; 'foo'
  @post.comments.build :text =&gt; 'bar'
  @post.comments.first # returns the new comment 'bar'
  @post.comments.first.post # returns nil :(
  @post.save # saves both post and comments simultaneously, in a transaction etc
  @post.comments.first # returns the comment 'bar'
  @post.comments.first.post # returns the post 'foo'
  </code></pre>
  
  <p>However, I need to be able to distinguish from within Comment (e.g. from its before_save or validation functions) between</p>
  
  <ol>
  <li>this comment is not attached to a post (which is invalid)</li>
  <li>this comment is attached to an <em>unsaved</em> post (which is valid)</li>
  </ol>
  
  <p>Unfortunately, merely calling <code>self.post</code> from Comment doesn't work, because per above, it returns nil until after save happens. In a callback of course, I don't (and shouldn't) have access to @post, only to self of the comment in question.</p>
  
  <p>So: how can I access the parent model of a new record's nested associations, from the perspective of that nested association model?</p>
  
  <p>(FWIW, the actual sample I'm using this with allows people to create a naked "comment" and will then automatically create a "post" to contain it if there isn't one already. I've simplified this example so it's not specific to my code in irrelevant ways.)</p>