2010-05-10 132 views
1

无外键我有一个嵌套形式有如下型号:在嵌套形式

​​

下面是创建一个新的事件控制器。

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 

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

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

我想我能做到这一点有:

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

,但不会出现工作就是我想要的。我如何将user_id附加到incident_note?

谢谢!

回答

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

我不认为你需要

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

new行动。你正在建造两次incident_notes

+0

如果我删除了,从新建,文本区域没有在视图中显示出来。但是,如果我从创建中删除它,它将修复重复。然而,在我的IncidentNotes表中设置user_id外键时仍存在问题: 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) 我是不知道如何将user_id设置为current_user标识。 – Magicked 2010-05-10 20:53:18