如何在 Rake 任务中使用 ActiveRecord 的迁移 DSL?

How to use ActiveRecord's migration DSL in Rake tasks?

我需要执行一些数据库操作,例如创建表、添加索引等。我想使用迁移中使用的相同方法,例如create_tableadd_index等。但是,当我尝试这个时,我得到

NoMethodError: undefined method `add_index' for main:Object

我在文件开头添加了这个:

include ActiveRecord::ConnectionAdapters::SchemaStatements

但是,现在我得到以下错误:

NameError: undefined local variable or method `allowed_index_name_length' for main:Object

这在 ActiveRecord::ConnectionAdapters::DatabaseLimits 中定义。我试图包括 ActiveRecord::ConnectionAdapters,但它并没有像我预期的那样包括所有 subclasses/modules。

所以问题是 - 我应该怎么做才能在迁移中编写我通常能够编写的相同代码?

你可以尝试直接使用ActiveRecord::Migration

>> f = ActiveRecord::Migration.new
>> f.connection.methods.grep(/^create/)
=> [:create_savepoint, :create, :create_database, :create_schema, :create_table, :create_join_table]
=> f.connection.methods.grep(/^add_index/)
=> [:add_index, :add_index_sort_order, :add_index_options]
=> f.connection.create_table(:awesome_table, force: true) do |t|
=>   t.string :foo  
=> end  
#> (44.0ms)  CREATE TABLE "awesome_table" ("id" serial primary key, "foo" character varying(255))
=> {}

迁移中的方法都是 ActiveRecord::Migration class 的 class 方法。所以你可以像

这样称呼它们
ActiveRecord::Migration.add_index :foo, :bar