Ruby-on-rails – Undefined method `update_attributes’ for nil:NilClass

rubyruby-on-rails

I'm working on a sort of auction/donation project and I want to change a attribute of a product, that is a boolean that indicates that the product has been donated.

The way that I'm doing it now is the following:

View:

<%= 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 %>

Controller:

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

routes:

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

And I'm getting the follwing error:

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

What am I doing wrong? Thanks and regards.

Best Solution

You have to first load the existing product and then update its attributes:

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