开发者

Nil foreign key in a nested form

开发者 https://www.devze.com 2022-12-30 06:44 出处:网络
I have a nested form with the following models: class Incident < ActiveRecord::Base has_many:incident_notes

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 w开发者_运维知识库as 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!


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号