我正在通过使用rails第4版(rails 3.2+)的敏捷web开发工作,并且有一个关于migraitons的问题。有一个练习,我必须将列添加到现有表中,然后使用值更新该新列。我需要在'line_items'表中添加'价格'列。首先,我产生的迁移:attr_accessible在迁移
rails generate migration add_price_to_line_items price:decimal
然后我编辑了迁移文件:
class AddPriceToLineItems < ActiveRecord::Migration
def change
add_column :line_items, :price, :decimal
LineItem.all.each do |li|
li.price = li.product.price
end
end
def down
remove_column :line_items, :price
end
end
一切工作按计划进行,但是,我有一个关于attr_accessible问题。我的理解是,对象的所有属性都需要在attr_accessible中指定才能编辑。如果没有,你通常会得到这样的错误:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: product
因此,所有属性必须被设置为在相关模型attr_accessible的参数:
class LineItem < ActiveRecord::Base
**attr_accessible :cart_id, :product_id, :quantity**
belongs_to :cart
belongs_to :product
def total_price
product.price * quantity
end
end
如果这是真的,那么如何为我的移民能够更新新生成的列?如果该列刚刚生成,那么该新属性将不会在关联模型的attr_accessible中指定。任何和所有的输入将不胜感激。