2013-10-08 38 views
0

我试图编辑模型,但它只是使用新的给定属性创建更多模型。试图编辑模型,不断创建更多(导轨)

我想我对方法和路线感到困惑。

/app/controllers/products_controller.rb

class ProductsController < ApplicationController 

    def new 
    end 

    def index 
    end 

    def create 
    @product = Product.create(params[:products]) 

    redirect_to @product 
    end 

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


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

    def update 
    @product.update_attributes(params[:id]) 
    @product.save 
    end 

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

    redirect_to "/products" 
    end 
end 

/app/views/products/edit.html.erb

<br /> 
<%= form_for @product do |f| %> 
    <%= f.label :title, "Title:" %> 
    <%= f.text_field :title, size: 20 %> 
    <br /><br /> 
    <%= f.submit "Update" %> 
<% end %> 

编辑

我更新了我的产品控制器和视图,但现在我得到一个零:NilClass错误。

+1

看着你创建行动 - 你知道'Model.create '自动保存?所以你也不需要'Model.save' – tommyd456

+1

控制器中没有'edit'动作,它应该是一个成员路径,例如'/ app/views/products /:id/edit.html.erb' – tihom

+0

是的 - 编辑操作用于显示编辑表单 - 数据然后提交到更新操作 – tommyd456

回答

3

只要用这个代替:

<%= form_for @product do |f| %> 

如果@product是一个新的记录,它会发布到您的create方法,如果它是一个现有的记录,它会发布到您的update方法。

update方法应该与此类似(你不需要调用saveupdate_attributes已经将它保存为你):

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