views:

45

answers:

2

I have a nested form with the following models:

class Incident < ActiveRecord::Base
  has_many                :incident_notes 
  belongs_to              :customer
  belongs_to              :user
  has_one                 :incident_status

  accepts_nested_attributes_for :incident_notes, :allow_destroy => false
end

class IncidentNote < ActiveRecord::Base
  belongs_to :incident
  belongs_to :user
end

Here is the controller for creating a new Incident.

def new
  @incident = Incident.new
    @users = @customer.users
    @statuses = IncidentStatus.find(:all)
    @incident.incident_notes.build(:user_id => current_user.id)

  respond_to do |format|
    format.html # new.html.erb
    format.xml  { render :xml => @incident }
  end
end

def create
  @incident = @customer.incidents.build(params[:incident])
  @incident.incident_notes.build(:user_id => current_user.id)

  respond_to do |format|
    if @incident.save
      flash[:notice] = 'Incident was successfully created.'
      format.html { redirect_to(@incident) }
      format.xml  { render :xml => @incident, :status => :created, :location => @incident }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @incident.errors, :status => :unprocessable_entity }
    end
  end
end

This all exists in a nested form for an incident. There is a text area for the incident_notes form that is nested in the incident.

So my problem is that the incident_notes entry is submitted twice whenever I create the incident. The first insert statement creates an incident_note entry with the text from the text area, but it doesn't attach the user_id of the user as the foreign key. The second entry does not contain the text, but it has the user_id.

I thought I could do this with:

@incident.incident_notes.build(:user_id => current_user.id)

but that does not appear to work the way I want. How can I attach the user_id to incident_note?

Thanks!

+1  A: 

I don't think you need

@incident.incident_notes.build(:user_id => current_user.id)

on new action. You're building the incident_notes twice.

j.
If I removed that from New, the text area didn't show up in the view. However, if I removed it from create, it fixed the duplication. However, I'm still having a problem getting the user_id foreign key to be set in my IncidentNotes table: IncidentNote Create (0.1ms) INSERT INTO "incident_notes" ("created_at", "updated_at", "user_id", "note", "incident_id") VALUES('2010-05-10 20:50:02', '2010-05-10 20:50:02', NULL, 'This is a note', 10)I'm not sure how to set the user_id as the current_user id.
Magicked
A: 

I finally figured it out. I needed to do this in the Incident controller:

def create
  @incident = @customer.incidents.build(params[:incident])
  @incident.incident_notes.first.user = current_user

rather than:

def create
  @incident = @customer.incidents.build(params[:incident])
  @incident.incident_notes.build(:user_id => current_user.id)
Magicked