2013-04-22 145 views
0

通过迁移插入新记录是否是一种很好的做法?最近,从头开始重新运行本地迁移时出现了一个奇怪的错误。它抛出一个这样的错误(例如:产品型号,成本列):Rails迁移问题

undefined method 'cost=' for #<Product:0x10f60f4b8>

迁移:

class AddNewProducts < ActiveRecord::Migration 
    def self.up 
    product1 = Product.new 
    product1.cost = 10 
    .... 
    product1.save! 
    end 
end 

成本在先前迁移加入:

Class AddCosttoProducts < ActiveRecord::Migration 

    def self.up 
     add_column :product, :cost, :integer, :default => 0, :null => false 
    end 

    def self.down 
     remove_column product, :cost 
    end 
end 

任何暗示为什么会发生?

+0

什么版本的导轨? – dpassage 2013-04-22 05:34:38

回答

1

如果您已经运行了先前的迁移(要添加cost字段),请尝试在添加记录之前重置列信息。

class AddNewProducts < ActiveRecord::Migration 
    def self.up 
    Product.reset_column_information 
    product1 = Product.new 
    product1.cost = 10 
    .... 
    product1.save! 
    end 
end 
+0

非常好,谢谢 – kasperite 2013-04-22 21:53:00