Matt Wolfe
Matt Wolfe

Reputation: 9294

Ruby rails 3 Nested Form fails to save because before_save method accesses a parent model whose object is nil

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..

So here is the simplified code

class Forum < ActiveRecord::Base
  has_many :forum_post, :dependent => :destroy
  belongs_to :project
  accepts_nested_attributes_for :forum_post,  :reject_if => :all_blank
end

class ForumPost < 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

Then in my ForumControler controller which updates this i have

def update
 @forum = Forum.find(params[:id])    
 if @forum.update_attributes(params[:forum])               
     redirect_to(user_forum_path(@user,@forum.project,@forum), :notice => 'Forum was successfully updated.')
  else        
     render :action => 'submit'        
  end

end

And in my view:

<%= form_for(@forum, :url => user_forum_path, :html => { :multipart => true, :id => :project } ) do |f| %>    
    <div class="form-label-row summary-text">
      <%= f.label(:summary_text, 'Final Summary') %>
      <%= f.text_area :summary_text %>
    </div>

    <%= f.fields_for :forum_post,$forum_post do |child_form| %>
        <div class="form-row-left attachment">
            <%= child_form.label :attachment %>
            <%= child_form.file_field :attachment %>    
        </div>
        <!-- I tried adding with and without the next 2 hidden fields and it failed either way -->
        <%= child_form.hidden_field :user_id, :value=>@user.id %>               
        <%= child_form.hidden_field :forum_id, :value=>@forum.id %>
    <% end %>

    <%= hidden_field(:forum, :state, :value => :student_completed) %>
    <div class="form-buttons" id="submit">
        <%= f.submit "Submit Project" %>
    </div>
<% end %>

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?

Upvotes: 2

Views: 515

Answers (1)

miked
miked

Reputation: 4509

Are you sure you want to use an instance variable and not the association? Try:

 def toggle_forum   
   #a bunch of code
   #one line tries to access @user.id but it fails because @user is nil
   user.id
 end

Upvotes: 2

Related Questions