2016-11-14 115 views
1

我目前正在开发Rails 4应用程序,并且在过去几个月中我收集了大量独特的迁移文件,这些文件可以反转它们自己的更改等。
由于我没有在这个开发阶段重置数据库的问题,我想我可能会清理一下这个混乱。

是否有重做所有迁移文件的方法,同时还允许删除某些迁移文件并扩展其他文件?Rails 4:将所有迁移重新迁移到Schema

我很欣赏每个答案!


实施例(编辑)

我有两个迁移文件:

  1. 20160911071103_create_items.rb
  2. 20160918085621_add_cached_votes_to_items.rb

两者都已迁移。前

class CreateItems < ActiveRecord::Migration 
    def change 
    create_table :items do |t| 

     t.integer :user_id 

     t.timestamps null: false 
    end 
    end 
end 

我的目标<

一号文件将包括由第二个文件直接在第一个文件并删除第二所添加的列。

一号文件作为你的意思是你后

class CreateItems < ActiveRecord::Migration 
    def change 
    create_table :items do |t| 

     t.integer :user_id 
     t.integer :cached_votes 

     t.timestamps null: false 
    end 
    end 
end 
+0

不知道您重做所有迁移文件**的含义是什么?你可以给你的应用程序的实例,我认为这会更有意义! – dp7

+0

@dkp增加了一个例子 – Gugubaight

+0

'rake db:reset' – jamesjaya

回答

1

你需要运行

rake db:migrate:down VERSION=20160918085621

rake db:migrate:down VERSION=20160911071103

您现在可以通过rake db:migrate:status检查迁移状态,你应该希望得到迁移状态如下:

down 20160911071103 
down 20160918085621 

现在,你可以删除迁移文件20160918085621_add_cached_votes_to_items.rb

&编辑迁移文件20160911071103_create_items.rb,因为你需要。

而且,最后运行:

rake db:migrate:up VERSION=20160911071103

+0

谢谢,这个原理的作品! – Gugubaight

0

它在发展只有这样你就可以更改迁移的文件。

注意:不建议编辑您的迁移,但不要在任何地方部署,因此您可以这样做。

20160911071103_create_items.rb

class CreateItems < ActiveRecord::Migration 
    def change 
    create_table :items do |t| 

     t.integer :user_id 

     t.timestamps null: false 
    end 
    end 
end 

20160918085621_add_cached_votes_to_items.rb

class AddCachedVotesToItems < ActiveRecord::Migration 
    def change 
    add_column :items, :cached_votes, :integer 
    end 
end 

修改你的第一个迁移和记得删除第二个迁移。

20160911071103_create_items。RB(迁移1 +迁移2)

class CreateItems < ActiveRecord::Migration 
    def change 
    create_table :items do |t| 

     t.integer :user_id 
     t.integer :cached_votes 

     t.timestamps null: false 
    end 
    end 
end 

然后DropMigrate再次

rake db:drop # Drop the db 

rake db:setup # Create and migrate the db 
0

,如果你有一个工作schema.rb文件。你可以生成一个迁移文件

bundle exec rails generate migration CreateItemsNew

然后从你的工作schema.rb这个新生成的迁移文件填写代码块create_table "items"。然后对db/migrate中的所有迁移进行批量搜索,这些迁移将更改表items并删除这些文件。通过这种方式,您将拥有一个用于数据库中表的单个迁移文件。