我正在进行一种拍卖/捐赠项目,我想更改产品的属性,这是一个表示产品已捐赠的布尔值。
我现在正在做的事情如下:
查看:
<%= 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"}
我做错了什么?谢谢和问候。
答案 0 :(得分:15)
您必须先加载现有产品,然后更新其属性:
def update
@product = Product.find_by_id(params[:id])
@product.update_attributes(params[:product])
flash[:success] = "Product donated!"
end