Search code examples
ruby-on-railsmass-assignment

Can't mass-assign protected attributes: integer


I am following a tutorial on Agile Web Development with Rails (4th edition)and on about page 112 i start getting an error

Can't mass-assign protected attributes: 2 

2 being the song_id. I am not using any '#attr_accessible' on the model. This start happening when i introduced this piece of code for a migration

class AddQuantityToLineItems < ActiveRecord::Migration
  def self.up
    add_column :line_items, :quantity, :integer, :default => 1
  end

  def self.down
    remove_column :line_items, :quantity
  end
end

and

class CombineItemsInCart < ActiveRecord::Migration
  def self.up
  Cart.all.each do |cart|
    sums = cart.line_items.group(:song_id).sum(:quantity)

    sums.each do |song_id, quantity|
    if quantity > 1
        cart.line_items.where(:song_id=>song_id).delete_all
        cart.line_items.create(:song_id=>song_id, :quantity=>quantity)
     end
    end
  end
  end

  def self.down
  LineItem.where("quantity>1").each do |line_item|

    line_item.quantity.times do

    LineItem.create :cart_id=>line_item.cart_id,
     :song_id=>line_item.song_id, :quantity=>1
    end
    line_item.destroy

    end
  end
end

Edit

After relooking at the co i realise that the error is in my controller. Which looks like this

def create @cart = current_cart song = Song.find(params[:song_id]) @line_item = @cart.line_items.build @line_item.song = song @line_item = @cart.add_song(song.id)

respond_to do |format|
  if @line_item.save
    format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
  else
    format.html { render action: "new" }
  end
end

This is the line causing problems

@line_item = @cart.add_song(song.id)


Solution

  • You have to add the line attr_accessible :quantity into line_item model, it will work!