title: Ruby rails 3 Nested Form fails to save because before_save method accesses a parent model whose object is nil
body: <p>I have a nested form/model in my rails app that would work ok except a before_save method does not have access to the parent @user object when working with the nested form.. It works fine though when saving the sub model itself though..</p>
  
  <p>So here is the simplified code</p>
  
  <pre><code>class Forum &lt; ActiveRecord::Base
    has_many :forum_post, :dependent =&gt; :destroy
    belongs_to :project
    accepts_nested_attributes_for :forum_post,  :reject_if =&gt; :all_blank
  end
  
  class ForumPost &lt; ActiveRecord::Base
      belongs_to :forum    
      belongs_to :user
      before_save :toggle_forum              
      has_attached_file :attachment
  
   def toggle_forum   
      #a bunch of code
      #one line tries to access @user.id but it fails because @user is nil
      @user.id
  
  
    end
  
   end
  </code></pre>
  
  <p>Then in my ForumControler controller which updates this i have</p>
  
  <pre><code>def update
   @forum = Forum.find(params[:id])    
   if @forum.update_attributes(params[:forum])               
       redirect_to(user_forum_path(@user,@forum.project,@forum), :notice =&gt; 'Forum was successfully updated.')
    else        
       render :action =&gt; 'submit'        
    end
  </code></pre>
  
  <p>end</p>
  
  <p>And in my view:</p>
  
  <pre><code>&lt;%= form_for(@forum, :url =&gt; user_forum_path, :html =&gt; { :multipart =&gt; true, :id =&gt; :project } ) do |f| %&gt;    
      &lt;div class="form-label-row summary-text"&gt;
        &lt;%= f.label(:summary_text, 'Final Summary') %&gt;
        &lt;%= f.text_area :summary_text %&gt;
      &lt;/div&gt;
  
      &lt;%= f.fields_for :forum_post,$forum_post do |child_form| %&gt;
          &lt;div class="form-row-left attachment"&gt;
              &lt;%= child_form.label :attachment %&gt;
              &lt;%= child_form.file_field :attachment %&gt;    
          &lt;/div&gt;
          &lt;!-- I tried adding with and without the next 2 hidden fields and it failed either way --&gt;
          &lt;%= child_form.hidden_field :user_id, :value=&gt;@user.id %&gt;               
          &lt;%= child_form.hidden_field :forum_id, :value=&gt;@forum.id %&gt;
      &lt;% end %&gt;
  
      &lt;%= hidden_field(:forum, :state, :value =&gt; :student_completed) %&gt;
      &lt;div class="form-buttons" id="submit"&gt;
          &lt;%= f.submit "Submit Project" %&gt;
      &lt;/div&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>The problem is that if @user is nil when saving the forum_post as a nested object.. If I save the forum_post in its own model it works fine. Any idea why the @user variable does not get populated when saving from the parent object?</p>