2013-10-08 36 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