Tallmaris
Tallmaris

Reputation: 7590

Rails separate DB migration not working

I am trying to run a migration to a separate DB in Rails, using establish_connection. I have something like this in the migration file:

def change
  ActiveRecord::Base.establish_connection("user_#{Rails.env}")
  ActiveRecord::Base.initialize_schema_migrations_table

  create_table "users", :force => true do |t|
    t.string   "email",  
end

In the yml I have this config:

user_development:
  adapter: postgresql
  encoding: unicode
  database: MyApp_user_development
  pool: 5
  host: localhost
  username: xxx
  password: xxx

Also I have defined the User Model like this:

class User < ActiveRecord::Base
  establish_connection "user_#{Rails.env}"
  [...]
end

Now, the DB exists but when running rake db:migrate I get this error:

==  CreateUserOnSeparateDb: migrating =========================================
rake aborted!
An error has occurred, this and all later migrations canceled:

connection is closed

Does any of you have any idea what is going on?

I have also tried to move the establish_connection call into a connection method in the migration file. In this case the table is created on migrate but then I get the same error (so somehow failing on other migrations) and by the way it does not create the schema_migrations table...

Any help?

Upvotes: 0

Views: 439

Answers (1)

Priyanka
Priyanka

Reputation: 11


Resolved above issue by following below steps.

class AddCustomTbl < ActiveRecord::Migration
def connection ActiveRecord::Base.establish_connection(Rails.env).connection end def up # Connection with user_#{Rails.env} oldEnv = Rails.env Rails.env = "user_#{Rails.env}" ActiveRecord::Base.establish_connection(Rails.env) create_table "users", :force => true do |t| t.string "email" end # Connection with Rails.env Rails.env = oldEnv ActiveRecord::Base.establish_connection ActiveRecord::Base.configurations[Rails.env] end def down # Connection with user_#{Rails.env} oldEnv = Rails.env Rails.env = "user_#{Rails.env}" ActiveRecord::Base.establish_connection(Rails.env).connection drop_table :users # Connection with Rails.env Rails.env = oldEnv ActiveRecord::Base.establish_connection ActiveRecord::Base.configurations[Rails.env] end end

Upvotes: 1

Related Questions