Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails ActiveModel::MassAssignmentSecurity::Error

I am trying to create line_items but I am getting this error

app/controllers/line_items_controller.rb:52:in `create'

which references to this line

Can't mass-assign protected attributes: product

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

the full code is below

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)
like image 416
thiagoh Avatar asked May 23 '26 18:05

thiagoh


1 Answers

You have to add attr_accessible :product in your LineItem class.

This is a security that forces you to whitelist which fields can be mass assigned in order to avoid hacks like github had ;)

like image 158
Intrepidd Avatar answered May 26 '26 13:05

Intrepidd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!