开发者

Execute migration files dynamically

How can we execute a mignation file dynamically from the source code. Means we want to execute a migration file from an action of开发者_Python百科 a controller. How can we do so?


The main issue was that we do not know the names of migration files. I do it with the following code

ActiveRecord::Migrator.migrate("vendor/plugins/#{self.id.to_s}/lib/db/migrate/", nil)
Package::Rake.call('db:schema:dump')

And the Rake class have the following method

def call(task, options={})
   options[:rails_env] = Rails.env
   args = options.map { |n,v| "#{n.to_s.upcase}='#{v}"}
   system "rake #{task} #{args.join(' ')} --trace >> #{Rails.root}/log/rake.log &"
end

Hope this will help some body with similar problems.


This is assuming the migration is static and in your db/migrate directory when the app server starts:

You could add the migrations directory to your autoload path in config/application.rb, and then require the migration file to be run inside your controller (or in a config initializer):

application.rb

config.autoload_paths += %W(#{Rails.root}/db/migrate)

your_controller.rb

require '20101209102033_some_migration_file'
#....
SomeMigrationFile.up

I would be interested to know what the use case is here. Seems pretty wild!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜