Nil外键以嵌套的forms出现

我有一个嵌套的表单与以下模型:

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

这是用于创建新事件的控制器。

 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 

这一切都以事件的嵌套forms存在。 fact_notes表单中有一个嵌套在事件中的文本区域。

所以我的问题是每当我创建事件时,events_notes条目都会提交两次。 第一个insert语句使用文本区域中的文本创建一个incident_note条目,但它不会将用户的user_id作为外键附加。 第二个条目不包含文本,但它具有user_id。

我以为我可以这样做:

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

但这似乎不像我想要的那样工作。 如何将user_id附加到incident_note?

谢谢!

我终于弄明白了。 我需要在事件控制器中执行此操作:

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

而不是:

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

我觉得你不需要

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

关于new行动。 你正在构建两次events_notes。