2013-05-02 163 views
1

我正在進行某種拍賣/捐贈項目,我想更改產品的屬性,即表示產品已捐贈的布爾值。未定義的方法`update_attributes'爲零:NilClass

,我現在做它的方式如下:

查看:

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

    <%= f.label "Are you sure you want to get this product?"%> 
    <%= f.check_box :donated%> 

    <%= f.submit "Receive!", class: "btn btn-large btn-primary" %> 
<% end %> 

控制器:

before_filter :signed_in_user, only: [:create, :destroy, :show, :index, :update] 
    ... 
    def update 
    @product.update_attributes(params[:product]) 
    flash[:success] = "Product donated!" 
    end 

路線:

resources :products, only: [:show, :create, :new, :update] 

我會得到follwing錯誤:

undefined method `update_attributes' for nil:NilClass 

app/controllers/products_controller.rb:30:in `update' 
Request 

Parameters: 

{"utf8"=>"✓", 
"_method"=>"put", 
"authenticity_token"=>"M9q/qVcDmVIlEx+T5VFF0YtkYtzHRUCZLkPkDjc7MJc=", 
"product"=>{"donated"=>"1"}, 
"commit"=>"Update product", 
"id"=>"1"} 

我在做什麼錯?感謝致敬。

回答

14

你必須首先加載現有的產品,然後更新其屬性:

def update 
    @product = Product.find_by_id(params[:id]) 
    @product.update_attributes(params[:product]) 
    flash[:success] = "Product donated!" 
end 
+0

運行完美,謝謝! – Bparra 2013-05-02 09:02:03

+0

很高興幫助。您可以將您的問題標記爲已解決。 – 2013-05-02 09:05:05

+0

@LazarusLazaridis在使用'@product = Product.find_by_id(params [:token])'而不是':id'加載的情況下,我仍然收到與你回答的問題相同的錯誤,我是什麼應該做的? – 2016-09-14 15:14:52

相關問題