I’m following the 4th Ed of Agile Web Dev with Rails. At Chapter 9 pg 112. I’m trying to run rake test:functional. I think I followed every piece of their code but it’s giving me a mass assign error. When I run the server, its giving me this error
ActiveModel::MassAssignmentSecurity::Error in LineItemsController#create
Can’t mass-assign protected attributes: product
This is how the LineItemsController create function looks like
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.line_items.build(product: product)
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 }
else
format.html { render action: "new" }
format.json { render json: @line_item.errors,
status: :unprocessable_entity }
end
end
end
Here is the create test in line_items_controller_test.rb in the folder test/functional/
test "should create line_item" do
assert_difference('LineItem.count') do
post :create, product_id: products(:ruby).id
end
assert_redirected_to cart_path(assigns(:line_item).cart)
end
What did I miss?
This was a recent change in the new version of Rails due to the Github fiasco: https://github.com/rails/rails/commit/b83965785db1eec019edf1fc272b1aa393e6dc57
To fix this you can do one of two things:
1) Change this setting (in your config/application.rb file) to
falseto allow mass-assignment site wide2) Whitelist all the attributes you’ll be changing by adding this line somewhere in your model:
The first is the old default way, and easier. The second is more secure for production apps.