Rails 4:重新迁移所有迁移到架构

时间:2016-11-14 05:43:15

标签: ruby-on-rails ruby database ruby-on-rails-4 migration

我目前正在开发一个Rails 4应用程序,在过去的几个月中,我收集了许多独特的迁移文件,这些文件可以反转他们自己的更改等。 由于我在开发的这个阶段没有问题重置db,我想我可以稍微清理一下这个烂摊子。

有没有办法重做所有的迁移文件,同时也是是否允许删除某些迁移文件并扩展其他文件?

我很欣赏每个答案!


示例(编辑)

我有两个迁移文件:

  1. 20160911071103_create_items.rb
  2. 20160918085621_add_cached_votes_to_items.rb
  3. 两者都已迁移。<

    之前的第一个文件

    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
    

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

如果您有一个有效的schema.rb文件。你可以生成一个迁移文件

bundle exec rails generate migration CreateItemsNew

然后将代码块create_table "items"从您正在工作的schema.rb填充到此新生成的迁移文件中。然后批量搜索db/migrate中更改表items并删除这些文件的所有迁移。这样,您就可以为数据库中的表创建一个迁移文件。