繁体   English   中英

nil:NilClass的未定义方法“ update_attributes”

[英]Undefined method `update_attributes' for nil: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]

我收到以下错误:

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"}

我究竟做错了什么? 谢谢并恭祝安康。

您必须首先加载现有产品,然后更新其属性:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM