2013-03-27 46 views
13

我正在用红宝石宝石构建Rails引擎。它包括一些迁移,现在被称为当您运行:通过发电机添加从Rails引擎宝石到应用程序的新迁移

rails g myengine:install 

生成器中的代码如下:

module MyEngine 
    module Generators 
    class InstallGenerator < ::Rails::Generators::Base 
     include Rails::Generators::Migration 

     source_root File.expand_path('../templates', __FILE__) 

     # ... 

     def copy_migrations 
     migration_template "migrations/migration1.rb", "db/migrate/migration1.rb" 
     migration_template "migrations/migration2.rb", "db/migrate/migration2.rb" 
     end 

     # ... 
    end 
    end 
end 

但是,如果我再次运行rails g myengine:install时,出现此错误:

Another migration is already named migration1: /Users/jh/Code/Web/demoapp/db/migrate/20130327222221_migration1.rb 

我希望它只是默默忽视的事实是已经有一个迁移,并继续到下一个迁移。 这样做的最佳方法是什么?

编辑:

每梅德的答案,这是我的解决方案:

def copy_migrations 
    copy_migration "migration1" 
    copy_migration "migration2" 
    end 

protected 

    def copy_migration(filename) 
    if self.class.migration_exists?("db/migrate", "#{filename}") 
     say_status("skipped", "Migration #{filename}.rb already exists") 
    else 
     migration_template "migrations/#{filename}.rb", "db/migrate/#{filename}.rb" 
    end 
    end 
+0

@Mischa,我的确在真实应用程序中拥有有意义的名字。当您重新运行安装生成器以升级它时,这没有帮助。 – 2013-04-01 17:12:47

+0

啊,我明白了。很高兴你解决了它... – Mischa 2013-04-02 00:09:57

回答

7

Rails中作为例子使用migration_template,你也许可以检查destination = self.class.migration_exists?(migration_dir, @migration_file_name),如果迁移已经存在,跳过打电话给migration_template

+0

这工作!谢谢德米特里。 – 2013-04-01 17:19:12

+0

'migration_exists?'工作。谢谢。只是为了清除。 'migration_exists?'需要两个字符串参数。 '@ migration_file_name'只在模板文件中可用 – 2015-05-20 07:40:03

相关问题