Reputation: 2478
Is it a good practice to insert new records through migration?Recently, I got a strange error when rerunning local migrations from scratch. It throws an errors like this(Eg: Product model, Cost column):
undefined method 'cost=' for #<Product:0x10f60f4b8>
Migration:
class AddNewProducts < ActiveRecord::Migration
def self.up
product1 = Product.new
product1.cost = 10
....
product1.save!
end
end
Column cost was added in a migration previously:
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
Any hint on why it happens?
Upvotes: 0
Views: 109
Reputation: 7616
If you already ran the previous migration (to add cost
field), try resetting column information before you add records.
class AddNewProducts < ActiveRecord::Migration
def self.up
Product.reset_column_information
product1 = Product.new
product1.cost = 10
....
product1.save!
end
end
Upvotes: 1