Ruby on Rails ActiveModel :: MassAssignmentSecurity :: Error

时间:2012-11-22 20:02:16

标签: ruby-on-rails ruby runtime-error

我正在尝试创建line_items,但我收到此错误

app / controllers / line_items_controller.rb:52:在'create'

引用此行

Can't mass-assign protected attributes: product

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

完整代码在

之下
class Product < ActiveRecord::Base

  attr_accessible :description, :image_url, :price, :title

   default_scope :order => 'title'

   has_many :line_items
   before_destroy :ensure_not_referenced_by_any_line_item
   #more code here...
   private

   # ensure that there are no line items referencing this product
   def ensure_not_referenced_by_any_line_item
     if line_items.empty?
       return true
     else
       errors.add(:base, 'Line Items present')
       return false
      end
   end

end



def create
   @cart = current_cart
   product = Product.find(params[:product_id])
   #the error is HERE!!
   @line_item = @cart.line_items.build(:product => product)

1 个答案:

答案 0 :(得分:3)

您必须在LineItem类中添加attr_accessible :product

这是一种安全措施,会强制您将哪些字段列入白名单,以避免像github那样的黑客攻击;)