2010-05-10 130 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