04 May 2012, 15:54

Vezu Sigidi (1 post)

Chapter 10 from page 112, i start getting an error

@ActiveModel::MassAssignmentSecurity::Error in LineItemsController#create@

Start complaining about mass assignment on protected atributes. I think it’s the product id, because my addres looks like this

@ @

and the error message looks like this

@ ActiveModel::MassAssignmentSecurity::Error in LineItemsController#create

Can’t mass-assign protected attributes: 2@

attr_accessibleOn my model i have not used #attr_accessible

I am using rails 3.2.3

can someone please help.

01 Jun 2012, 20:15

Mark Rall (1 post)

Chapter 9, page 112 of the PDF has a similar problem.

Can't mass-assign protected attributes: product
app/controllers/line_items_controller.rb:45:in `create'

I’ve tried the advice at theengguy, adding more attr_accessible attributes to the LineItems and Product models - no luck.

ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin11.4.0]
Rails 3.2.3

Please help. Thanks!

07 Jun 2012, 16:33

Jerome Marchand (2 posts)

the order of things done imacts this matter.

I had a similiar issue under iteration D3. My line_item model had attr_accessible :product_id, :cart_id

On a hunch a commented the line out and things passed through. Works, but I don’t know if it may subject to mass-assignment… We’ll see if further on this matter gets addressed with proper handling of the process.

30 Apr 2013, 23:36
Santafe photo_pragsmall

Bradford Arner (1 post)

The create() method in LineItemsController should be as follows:

def create
    @cart = current_cart
    product = Product.find(params[:product_id])
    @line_item = @cart.line_items.build(product_id: product.id)

    respond_to do |format|
      if @line_item.save
        format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
        format.json { render json: @line_item, status: :created, location: @line_item }
        format.html { render action: "new" }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }

The key difference is what you are passing into the build() method. The book says it should be: @line_item = @cart.line_items.build(product: product)

However, it should be now be: @line_item = @cart.line_items.build(product_id: product.id)

This is to protect against the Mass Assignment security issue. In other words, all that you have to do is clearly identify that you are assigning the product.id to the product_id column in the LineItem table.

I’m not sure if they have updated the book yet but the one that I was going through was from the library, so it may have been a previous edition.

  You must be logged in to comment