0

我正在通過Agile Web Dev w/Rails圖書(第4版)工作,並且我完全卡住了... 我正在運行Rails 3.2.3 on Mac OSX。 IM在任務d-3:添加一個按鈕 ....它開始與測試:在本章結尾沒有工作函......它給了我一個錯誤說:帶有Rails的敏捷Web開發(第4版)購物車問題

Can't Mass assign protected attributes: product 

我其次這裏給出的建議是:http://forums.pragprog.com/forums/148/topics/10565

,並改變了我的代碼行中Line_Items_Controller到

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

這裏是我當前Line_Items_Controller創建方法如下所示:

# 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 

現在我得到這個奇怪的消息:

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

,這裏是我的LineItem模型

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

林真的不知道該怎麼在這一點上做的,因爲我是一個總Rails(& Ruby)newb。 任何人都可以指向正確的方向嗎?

+0

需要查看LineItem模型。 – meagar

回答

2

更改原始代碼行 @line_item = @cart.line_items.build(product: product)@line_item = @cart.line_items.build(:product_id => product.id)line_items_controller.rb爲我解決了這個問題。

+0

太棒了!非常感謝你...這固定了一切 –

0

您的訂單項模型沒有ActiveRecord產品關聯。我不知道你正在構建什麼,但我想你會想:

#lineitem 
belongs_to :produce 

#product 
has_many :line_items 

你還需要的product_id添加到您的訂單項表格。

1

在我的情況有:PRODUCT_ID中的LineItem attr_accessible:

attr_accessible :cart_id, :product_id 

,所以我改變:產品=>產品在建的屬性:PRODUCT_ID => product.id和它的作品。

@line_item = @cart.line_items.build(:product_id => product.id) 
1

,如果你想從書中的例子工作正是他們鍵入它的方式,去模特/ line_item.rb並添加attr_accessible看起來像這樣;

attr_accessible :cart_id, :product_id, :product 

n'joy。