手动更新模型后更新db / migrate?

例如,我有这个模型:

class Product < ActiveRecord::Base attr_accessible :name, :order end 

然后,当我做rake db:migrate它创建了这个db / migrate / 20120825132038_create_products.rb

 class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.integer :order t.string :name t.timestamps end end end 

但这一切都发生了因为我使用了rails generate Product order:integer name:string

现在我转到产品型号并手动更改为:

 class Product < ActiveRecord::Base attr_accessible :name, :order, :category_id validates :name, uniqueness: true belongs_to :category end 

如何使用更新自动更新db / migrate / 20120825132038_create_products.rb

运行rake db:migrate ,它没有创建db/migrate/20120825132038_create_products.rb 。 您运行时创建了该迁移文件

 rails generate Product order:integer name:string 

attr_accessible与迁移数据库无关。

我强烈建议您阅读有关迁移的Rails指南,以及有关attr_accessible Mass Assignment部分。

要生成新的迁移文件(因为您的问题中提到的文件已经由您提到的上一个rake db:migrate命令处理) ,运行

 rails g migration AddCategoryIdToProduct category_id:integer 

这应该生成一个包含内容的新迁移

 class AddCategoryIdToProduct < ActiveRecord::Migration def change add_column :products, :category_id, :integer end end 

现在再次运行rake db:migrate将处理此迁移文件,将新的category_id整数列添加到products表中。

您可以通过运行重做迁移

 rake db:migrate:up VERSION=20121031143418 #insert the timestamp on migration 

您也可以重做一次迁移(上下运行,但只有在你有一个向上和向下的情况下才能运行,当你只有一个变化时就不会这样做)

 rake db:migrate:redo