PUT-ing表格来更新一行,但我找不到id。它在哪里?

时间:2010-06-16 22:00:56

标签: ruby-on-rails ruby

我应该如何传递ID?

错误:

  

找不到没有ID的产品

形式:

<% form_for :product, @product, :url => { :action => :update } do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :names %><br />
    <%= f.text_field :names %>
  </p>
  <p>
    <%= f.submit 'Update' %>
  </p>
<% end %>

控制器(用于/ products / edit / 1视图):

def edit
  @product = Product.find(params[:id])
end

控制器(更改数据库):

def update
    @product = Product.find(params[:id])

    respond_to do |format|
      if @product.update_attributes(params[:product])
        format.html { redirect_to(@product, :notice => 'Product was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

2 个答案:

答案 0 :(得分:2)

尝试从form_for语句中删除:product

修改:尝试删除网址选项。问题是您发布到的URL没有id属性。

答案 1 :(得分:2)

此表格标签应该足够了:

<% form_for @product do |f| %>

确保在config / routes.rb中有这一行:

map.resources :products

要获得额外的功劳,您可以使用before_filter简化在控制器中加载@product:

class ProductsController < ApplicationController
  before_filter :load_product, :only => [:show, :edit, :update, :destroy]
  def load_product
    @product = Product.find(params[:id])
  end
end