最近在学习Ruby on Rails…
开始按照书上的例子程序搭建系统.
第八章完成以后.保存了版本.然后开始兴致高昂的进入第九章.添加一个Add to Cart 按钮这一小节.
顺利的step by step 完成了界面以及后台代码的改写.
运行起服务器
当我点击页面的 Add to Cart的时候结果却不是希望的那样.

# POST /line_items
  # POST /line_items.json
  def create
    #@line_item = LineItem.new(params[:line_item])
    @cart = current_cart
    product = Product.find(params[:product_id])
    @lint_item = @cart.line_items.build(:product => product)
    respond_to do |format|
      if @line_item.save
        ...........

在页面就报错了:
ActiveModel::MassAssignmentSecurity::Error in LineItemsController#create
Can’t mass-assign protected attributes: product
基于这个错误我去谷歌了一把.
看到了这样的一个网页

http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-accessible_attributes

应为根据报错的内容,我怀疑是line_item不能获取到product.接下来我修改了 line_item.rb的model

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

点击按钮还是报错了.这回不是product protected了
NoMethodError in LineItemsController#create
undefined method `save’ for nil:NilClass
再次谷歌一把.在一个英文的帖子发现了同样的问题.阅读了一下网友的回复找到了解决办法
问题还是出在@lint_item = @cart.line_items.build(:product => product)这句话
修改line_items_controller.rb文件,将@lint_item = @cart.line_items.build(:product => product)替换为

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

通过以上修改就能正确的运行新添加的功能.具体的原因我还在思考..如果您知道欢迎你在下面留言.

 

原因在此
http://guides.rubyonrails.org/security.html#mass-assignment
为了安全考虑,如果允许mass-assignment的话,可以通过链接往数据库里插入数据,我也看到这一章碰到同样的问题了
所以默认不可以直接用build来new这个新对象,除非你加上
attr_accessible :product,:cart
显示告诉他们你允许mass-assignment
 posted on 2012-04-27 13:25  Shadow.R  阅读(2719)  评论(5编辑  收藏  举报