Rails生成迁移

我目前已经有了名为Products的迁移,我只是想为这个迁移添加更多的string,比如描述和产品types。 做这个的最好方式是什么?

class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.decimal :price t.text :description t.timestamps end end end 

赶紧跑

 rails g migration add_description_to_products description:string rails g migration add_product_type_to_products product_type:string 

然后运行

 rake db:migrate 

在任何实际应用程序的开发中,您将会进行相当多的迁移,这些迁移基本上是DDL(数据定义语言)语句。 在现实生活中,您将拥有多种环境(开发,testing,生产等),而且在生产版本中,您很可能会更改开发数据库。 出于这个原因,Rails的方式是为数据库的任何更改生成新的迁移,而不是直接更改现有的迁移文件。

所以,要熟悉一下迁移。

对于具体的问题,你可以这样做:

 rails g migration add_attributes_to_products attr1 attr2 attr3 

这将生成一个新的迁移文件,用于将3个新属性添加到产品表(到产品模型)。 属性的默认types是string 。 对于其他人,你已经指定它:

 rails g migration add_attributes_to_products attr1:integer attr2:text attr3:enum 

假设你创build了上面的迁移表,然后添加product_type(你已经有了描述),你可以这样做:

 # db/migrate/20130201121110_add_product_type_to_product.rb class AddProductTypeToProduct < ActiveRecord::Migration def change add_column :products, :product_type, :string Product.all.each do |product| product.update_attributes!(:product_type => 'unknown') end end end 

如果最后一个操作是migration请使用rollback

 rake db:rollback 

然后在迁移文件中添加属性

 class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.decimal :price t.text :description t.string :product_type #adding product_type attribute to the products table t.timestamps end end end 

之后,迁移使用

 rake db:migrate 

如果迁移不是您的最后一个操作,请按照上述答案生成新的迁移文件

 rails g migration add_attributes_to_products product_type:string 

上面的代码只生成迁移文件,但是您想使用rake db:migrate来迁移文件。

如果您想对迁移文件进行任何更改(例如添加更多属性),请在迁移之前进行,否则,如果最后一个操作是迁移,或者您需要生成另一个迁移文件,则必须使用前面提到的方法。 检查这个链接了解更多关于迁移http://guides.rubyonrails.org/v3.2.8/migrations.html

耙生成迁移add_description_to_products

 AddDescriptionToProducts < ActiveRecords:: Migration[v] def change add_column :products :description :string add_column :name_of_table :name_of_column :data_type end 

运行rake db:migrate,你的schema.rb应该被更新