我有一個非常類似的問題(不是很確定,如果是完全一樣的),因爲這帖子:Ruby on Rails的編輯/更新方法是創建一個新的對象,而不是更新
Edit method is creating new records, instead of just updating existing ones
^^您可能注意到,沒有發佈解決方案。
我有一張爲我們建築物的網絡設置的地圖。它被設置爲樓層=>開關,開關=>插孔。每個只嵌套一次。
問題出在我的開關編輯/更新方法。當我點擊一個開關的編輯按鈕時,它會將我重定向到正確的URL(.../switch/1/edit),但我馬上注意到表單不正確。而不是按鈕說「更新開關」,它說「創建開關」,這正是發生了什麼。一個新的開關被創建,而不是我想要更新的開關被更新。
這是相關的代碼。如果你想看到其他東西,請告訴我。
...應用程序/視圖/開關/ _form.html.erb:
<%= form_for([@floor, @switch]) do |f| %>
<% if @switch.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@switch.errors.count, "error") %> prohibited this switch from being saved:</h2>
<ul>
<% @switch.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
...應用程序/控制器/ switches_controller.rb:
class SwitchesController < ApplicationController
def create
@floor = Floor.find(params[:floor_id])
@switch = @floor.switches.create(params[:switch])
redirect_to(@floor)
end
def destroy
@floor = Floor.find(params[:floor_id])
@switch = @floor.switches.find(params[:id])
@switch.destroy
redirect_to(@floor)
end
def show
@floor = Floor.find(params[:floor_id])
@switch = @floor.switches.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @switch }
end
end
def edit
@floor = Floor.find(params[:floor_id])
@switch = @floor.switches.find(params[:id])
end
def update
@floor = Floor.find(params[:id])
@switch = @floor.switches.find(params[:id])
respond_to do |format|
if @switch.update_attributes(params[:switch])
format.html { redirect_to @switch, :notice => 'Floor was successfully updated.' }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => @switch.errors, :status => :unprocessable_entity }
end
end
end
end
誰能幫助找出原因它會去創建方法而不是更新?謝謝!
我嘗試了你的第一個建議(改變了行,刪除了第二個),現在我甚至都看不到地板。 未定義的方法'模型名稱」的NilClass:類 提取的源(圍繞線#1): 1:<(%)=的form_for([@地板,@switch])做| F | %> –
我也加了新的方法。 –
您可能會在另一個控制器中呈現新swith的表單,因爲它之前沒有「新」動作。請檢查哪個動作呈現表單並在其中添加「@switch = @ floor.switches.build」。 – dimuch