Search code examples
ruby-on-railscontrollerfunctional-testingcartnomethoderror

Agile Web Development w/ Rails (4th e) Cart Issue


I'm working through Agile Web Dev w/ Rails book (4th ed) and I'm totally stuck... I'm running Rails 3.2.3 on Mac OSX. Im on task D-3: Adding a Button.... it started with the test:functionals not working at the end of the chapter... it gave me an error saying:

Can't Mass assign protected attributes: product

I followed the advice given here: http://forums.pragprog.com/forums/148/topics/10565

and changed my line of code in the Line_Items_Controller to

@line_item = @cart.line_items.build
@line_item.product = product 

Here is what my current Line_Items_Controller create method looks like:

# POST /line_items

def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build
@line_item.product = product

respond_to do |format|
  if @line_item.save
    format.html { redirect_to(@line_item.cart,
      :notice => 'Line item was successfully created.') }
    format.xml  { render :xml => @line_item,
      :status => :created, :location => @line_item }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @line_item.errors,
      :status => :unprocessable_entity }
  end
end
end

Now I am getting this weird message:

NoMethodError in LineItemsController#create undefined method `product=' for   <LineItem:0x000001024f7fb0>

Here is my LineItem model

   class LineItem < ActiveRecord::Base
  attr_accessible :cart_id, :product_id, :product
end

Im not really sure what to do at this point, since I'm a total Rails (& Ruby) newb. Can anyone point me in the right direction?


Solution

  • Changing the original line of code @line_item = @cart.line_items.build(product: product) to @line_item = @cart.line_items.build(:product_id => product.id) in line_items_controller.rb solved this problem for me.