我有一个非常类似的问题(不是很确定,如果是完全一样的),因为这帖子: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