[英]Rails — Possible to run migration methods in generic rake task?
I know this is not best practice, and most likely shouldn't even be used, as thats what migrations are used for, but I was wondering if its possible to execute migration specific commands in a regular rake task. 我知道这不是最佳实践,并且很可能甚至不应该使用,因为迁移的用途是什么,但我想知道是否可以在常规rake任务中执行特定于迁移的命令。 Something like:
就像是:
namespace :dummy do
task :update => :environment do
add_column :users, :deleted, :boolean, { :null => false, :default => false }
end
end
Thanks 谢谢
It is possible to run arbitrary pseudo-migrations in your rake tasks: 可以在rake任务中运行任意伪迁移:
namespace :dummy do
task :update => :environment do
ActiveRecord::Base.connection.add_column :users, :deleted, :boolean, :null => false, :default => false
end
end
If you're doing a lot of that sort of thing, use short-hand: 如果你做了很多这样的事情,请使用简写:
namespace :dummy do
task :update => :environment do
c = ActiveRecord::Base.connection
c.add_column :users, :deleted, :boolean, :null => false, :default => false
end
end
Yes, you should do something like this: 是的,你应该做这样的事情:
namespace :dummy do
task :update => :enviroment do
ActiveRecord::Migration.send(:add_column, :users, :deleted, :boolean, { :null => false, :default => false })
end
end
Not tested, but the important thing here is to include the migration class and then send the method you wish to run. 没有经过测试,但重要的是包含迁移类,然后发送您希望运行的方法。
UPDATED to use ActiveRecord::Migration
directly via @tadman 更新为直接通过@tadman使用
ActiveRecord::Migration
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.