代码之家  ›  专栏  ›  技术社区  ›  montooner

用表格更新一行,但找不到ID。它在哪里?

  •  0
  • montooner  · 技术社区  · 14 年前

    我该怎么输入身份证?

    错误:

    找不到没有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 回复  |  直到 14 年前
        1
  •  2
  •   Maz    14 年前

    尝试从表单中删除:product for语句

    编辑: 也尝试删除URL选项。问题是您要发布到的URL没有ID属性。

        2
  •  2
  •   elektronaut    14 年前

    此表单标记应足够:

    <% form_for @product do |f| %>

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

    map.resources :products

    对于额外的学分,您可以使用 before_filter :

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