Alexander Popov
Alexander Popov

Reputation: 25005

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

I need to perform some database manipulations, such as creating tables, adding indexes etc. I would like to use the same methods used in migrations, such as create_table, add_index etc. However, when I try this I get

NoMethodError: undefined method `add_index' for main:Object

I added this at the beginning of my file:

include ActiveRecord::ConnectionAdapters::SchemaStatements

However, now I get the following error:

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

This is defined in ActiveRecord::ConnectionAdapters::DatabaseLimits. I tried to include ActiveRecord::ConnectionAdapters, but it didn't include all subclasses/modules, as I expected.

So the question is - what should I do in order to be able to write the same code I am normally able to write within a migration?

Upvotes: 1

Views: 434

Answers (2)

Max Williams
Max Williams

Reputation: 32955

The methods in a migration are all class methods of the ActiveRecord::Migration class. So you can call them like

ActiveRecord::Migration.add_index :foo, :bar

Upvotes: 2

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

You can try to use ActiveRecord::Migration directly:

>> 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))
=> {}

Upvotes: 2

Related Questions