我正在关注关于使用 Rails 进行敏捷 Web 开发(第 4 版)的教程,在第 112 页上我开始收到错误消息
Can't mass-assign protected attributes: 2
2 是 song_id。我没有在模型上使用任何“#attr_accessible”。当我介绍这段代码进行迁移时,这种情况就开始发生了
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
和
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
编辑
重新查看 co 后,我意识到错误在我的控制器中。看起来像这样
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
这是导致问题的线路
@line_item = @cart.add_song(song.id)