我正在阅读敏捷网络开发/ Rails书(第4版),我完全被困住了.我在Mac上运行Rails 3.2.3。I在任务D-3:添加按钮.它以测试开始:功能函数在本章末尾不起作用.它给了我一个错误,说:
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。谁能给我指明正确的方向?
发布于 2012-05-09 15:50:53
将原来的代码@line_item = @cart.line_items.build(product: product)改为@line_item = @cart.line_items.build(:product_id => product.id) in line_items_controller.rb为我解决了这个问题。
发布于 2012-07-10 16:44:50
在我的例子中,有:product_id In LineItem attr_accessible:
attr_accessible :cart_id, :product_id因此,我更改了:build的属性中的产品=>产品:product_id => product.id,它可以工作。
@line_item = @cart.line_items.build(:product_id => product.id)发布于 2012-08-21 17:04:01
如果您想让书中的示例完全按照他们键入的方式工作,请转到models/line_item.rb并添加attr_accessible,如下所示;
attr_accessible :cart_id, :product_id, :product恩乔伊。
https://stackoverflow.com/questions/10508158
复制相似问题