Ruby on Rails编辑/更新方法正在创建一个新对象而不是更新

时间:2012-06-19 19:20:16

标签: ruby-on-rails ruby-on-rails-3 networking network-programming

我有一个非常类似的问题(不太确定它是否完全相同),这篇文章:

Edit method is creating new records, instead of just updating existing ones

^^您可能会注意到,没有发布解决方案。

我为我们的建筑网络设置了地图。它设置为floor =>开关,开关=>插孔。每个只嵌套一次。

问题在于我的切换编辑/更新方法。当我点击开关的编辑按钮时,它会将我重定向到正确的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

任何人都可以帮忙弄清楚它为什么会使用create方法而不是更新?谢谢!

1 个答案:

答案 0 :(得分:0)

错误在这里,表格总是为新开关构建

<%= form_for([@floor, @floor.switches.build]) do |f| %>
  <% @switch = @floor.switches.find(params[:id]) %>

将其更改为

<%= form_for([@floor, @switch]) do |f| %>

(并删除行)

<% @switch = @floor.switches.find(params[:id]) %>

我在控制器中看不到new动作,它看起来像

def new
  @floor = Floor.find(params[:floor_id])
  @switch = @floor.switches.build
end