Nil外键以嵌套形式出现

时间:2010-05-10 17:24:37

标签: ruby-on-rails

我有一个嵌套的表单,其中包含以下模型:

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

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

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

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

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

我以为我可以这样做:

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

但这看起来并不像我想要的那样。如何将user_id附加到incident_note?

谢谢!

2 个答案:

答案 0 :(得分:2)

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

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)

答案 1 :(得分:1)

我觉得你不需要

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

on new行动。您正在构建incident_notes两次。

相关问题