Search code examples
ruby-on-railsrubydatabaserakedbmigrate

Rails db:migrate cannot mass assign protected attributes


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?


Solution

  • Can't mass-assign protected attributes: quantity

    try attr_accessible :quantity

    you will need to list all of the attributes in that list.