Can't mass-assign protected attributes: quantity
try attr_accessible :quantity
you will need to list all of the attributes in that list.
题
I am learning Rails with the book Agile Web Development with Rails 4th edition.
Given the code for the migration below:
class CombineItemsInCart < ActiveRecord::Migration
def up
Cart.all.each do |cart|
sums = cart.line_items.group(:product_id).sum(:quantity)
sums.each do |product_id, quantity|
if quantity > 1
cart.line_items.where(product_id: product_id).delete_all
cart.line_items.create(product_id: product_id, quantity: quantity)
end
end
end
end
def down
LineItem.where("quantity>1").each do |line_item|
line_item.quantity.times do
LineItem.create(cart_id: line_item.cart_id, product_id: line_item.product_id, quantity: 1)
end
line_item.destroy
end
end
end
The following error occurs:
== CombineItemsInCart: migrating =============================================
rake aborted!
An error has occurred, this and all later migrations canceled:
Can't mass-assign protected attributes: quantity/home/richard/projects/pickaxe/mini-projects/depot-app/db/migrate/20130607003533_combine_items_in_cart.rb:9:in `block (2 levels) in up'
/home/richard/projects/pickaxe/mini-projects/depot-app/db/migrate/20130607003533_combine_items_in_cart.rb:6:in `each'
/home/richard/projects/pickaxe/mini-projects/depot-app/db/migrate/20130607003533_combine_items_in_cart.rb:6:in `block in up'
/home/richard/projects/pickaxe/mini-projects/depot-app/db/migrate/20130607003533_combine_items_in_cart.rb:3:in `each'
/home/richard/projects/pickaxe/mini-projects/depot-app/db/migrate/20130607003533_combine_items_in_cart.rb:3:in `up'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Now I read somewhere that this book was written before attr_accessible was required by default, but it hasnt really touched on how to use it properly yet. I have tried adding :line_item or :line_items to my attr_accessible line in the Cart model, but no luck.
Could someone educate me on what is happening here?
解决方案
Can't mass-assign protected attributes: quantity
try attr_accessible :quantity
you will need to list all of the attributes in that list.
其他提示
You need to make the attributes accessible. In the model:
class Object ActiveRecord::Base
attrib_accessible :attrib1, :attrib2, :attrib3
end
Obviously you would replace the attrib1 etc. with your model's attributes.
You try to access mass attributes from your migration. When you want to access database table attributes from your code then you need to allowing mass assignment of that attributes to tell your model that you can able to assign data for the field by the code. For this pusrpose, just add the desired field as a attr_accessible and for your issue specific solution is bellow :
class LineItem < ActiveRecord::Base
attr_accessible :quantity, :product_id, :cart_id
end