Rails migration: establish_connection creates table in wrong database
Asked Answered
M

3

3

I want to create a new table in a database other than the one defined in my database.yml file.

Here's my database.yml file:

development:                                                                                                                                                                    
  adapter: mysql2                                                                                                                                                               
  encoding: utf8                                                                                                                                                                
  reconnect: false                                                                                                                                                              
  database: main_development                                                                                                                                                    
  pool: 5                                                                                                                                                                       
  username: root                                                                                                                                                                
  password:                                                                                                                                                                     
  socket: /var/run/mysqld/mysqld.sock                                                                                                                                           

test:                                                                                                                                                                           
  adapter: mysql2                                                                                                                                                               
  encoding: utf8                                                                                                                                                                
  reconnect: false                                                                                                                                                              
  database: main_test                                                                                                                                                    
  pool: 5                                                                                                                                                                       
  username: root                                                                                                                                                                
  password:                                                                                                                                                                     
  socket: /var/run/mysqld/mysqld.sock  

production:                                                                                                                                                                           
  adapter: mysql2                                                                                                                                                               
  encoding: utf8                                                                                                                                                                
  reconnect: false                                                                                                                                                              
  database: main_prod                                                                                                                                                    
  pool: 5                                                                                                                                                                       
  username: root                                                                                                                                                                
  password:                                                                                                                                                                     
  socket: /var/run/mysqld/mysqld.sock  

I have another database called "peripheral". I'd like to create a table inside that database called "retailer_to_domain".

Here's my migration file:

class CreateRetailerToDomains < ActiveRecord::Migration                                                                                                                         

      def connection                                                                                                                                                                
        ActiveRecord::Base.establish_connection(                                                                                                                                    
        :adapter => "mysql2",                                                                                                                                                       
        :encoding => "utf8",                                                                                                                                                        
        :reconnect => false,                                                                                                                                                        
        :database => "peripheral",                                                                                                                                                 
        :pool => 5,                                                                                                                                                                 
        :username => "root",                                                                                                                                                        
        :password => "",                                                                                                                                                            
        :socket => "/var/run/mysqld/mysqld.sock").connection                                                                                                                        
      end                                                                                                                                                                           

      def change                                                                                                                                                                    
        ActiveRecord::Base.connection.create_table :retailer_to_domains do |t|                                                                                            
          t.string :name                                                                                                                                                            
          t.string :domain                                                                                                                                                          

          t.timestamps                                                                                                                                                              
        end                                                                                                                                                                         
      end                                                                                                                                                                           
    end           

The migration file was generated by the command: rails generate model RetailerToDomain name:string domain:string and then I added the def connection method to override the default database ("main") from the database.yml configuration.

When I run the migration (rake db:migrate) the retailer_to_domains table gets created in the main_development database. How do I override this default to get the migration to create the table where I want it?

Also, I expect the RetailerToDomain model to access this table in a similar manner with the establish_connection method looking like this:

class RetailerToDomain < ActiveRecord::Base                                                                                                                                     

 establish_connection(                                                                                                                                    
            :adapter => "mysql2",                                                                                                                                                       
            :encoding => "utf8",                                                                                                                                                        
            :reconnect => false,                                                                                                                                                        
            :database => "peripheral",                                                                                                                                                 
            :pool => 5,                                                                                                                                                                 
            :username => "root",                                                                                                                                                        
            :password => "",                                                                                                                                                            
            :socket => "/var/run/mysqld/mysqld.sock")

self.table=retailer_to_domain

validates_presence_of :name, :domain

end  

Thanks in advance for any ideas here!

Mulciber answered 18/8, 2012 at 19:43 Comment(0)
C
4

watch this page!

https://github.com/rails/rails/issues/3497

create rake file

# Augment the main migration to migrate your engine, too.
task 'db:migrate', 'your_engine:db:migrate'

# Augment to dump/load the engine schema, too
task 'db:schema:dump', 'your_engine:db:schema:dump'
task 'db:schema:load', 'your_engine:db:schema:load'

namespace :your_engine do
  namespace :db do
    desc 'Migrates the your_engine database'
    task :migrate => :environment do
      p "your_engine db migrate"
      with_engine_connection do
        ActiveRecord::Migrator.migrate("#{File.dirname(__FILE__)}/../../db/migrate/your_engine", ENV['VERSION'].try(:to_i))
      end
      Rake::Task['your_engine:db:schema:dump'].invoke
    end

    task :'schema:dump' => :environment do
      require 'active_record/schema_dumper'

      with_engine_connection do
        File.open(File.expand_path('../../../db/your_engine_schema.rb', __FILE__), 'w') do |file|
          ActiveRecord::SchemaDumper.dump ActiveRecord::Base.connection, file
        end
      end
    end

    task :'schema:load' => :environment do
      with_engine_connection do
        load File.expand_path('../../../db/your_engine_schema.rb', __FILE__)
      end
    end
  end
end

# Hack to temporarily connect AR::Base to your_engine.
def with_engine_connection
  original = ActiveRecord::Base.remove_connection
  ActiveRecord::Base.establish_connection "your_engine_#{Rails.env}".to_sym
  yield
ensure
  ActiveRecord::Base.establish_connection original
end

model

class YourModel < ActiveRecord::Base
    establish_connection "your_engine_#{Rails.env}".tom_sym
end

database.yaml

your_engine_development:
  adapter: 
  database:
  encoding:
  username:
  password:
  host:
Contumacious answered 24/3, 2014 at 12:49 Comment(0)
G
1

In your config/database.yml:

new_connect_development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: new_database_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

And the same block for all others environments. Then add to your migrations (example for rails 2.x-3.0, for rails 3.1 remove self):

  def self.connection
    ActiveRecord::Base.establish_connection("new_connect_#{RAILS_ENV}").connection
  end

And add following lines to your model, which corresponding with table in new database:

class ModelName < ActiveRecord::Base
  establish_connection "new_connect_#{RAILS_ENV}"
end
Groundspeed answered 28/2, 2013 at 15:49 Comment(4)
At least in Rails >= 4.0 you should use Rails.env instead of RAILS_ENV. This was bugging me.Tlaxcala
I'm using Rails 4, I failed to do migration, getting error like SQLite3::SQLException: table "table_name" already exists. I already setup both mysql2 and sqlite connections in database.yml. What does the error mean? Please help!Lawful
Oh, I found my error, I'm using Rails 4, so def self.connection is needed. I forgot the self method :)Lawful
I know it's very old but it solved a frustrating problem for me. I had a problem only in test env, where establish_connection wasn't "remembered" (or how to say it). connection_config was showing the changed db but queries was using the "main" db. I posted an answer to this question https://mcmap.net/q/267261/-rspec-how-to-run-tests-on-a-different-database. I think the question here isn't exactly my problem. But thanks a lot! It gave me a tip of how to solve it, it shouldn't be necessary to do it like this I think, but it works...Contemn
P
0
        Add another database connection seeting to database.yml file.

        database.yml file

            development:                                                                                                                                                                    
              adapter: mysql2                                                                                                                                                               
              encoding: utf8                                                                                                                                                                
              reconnect: false                                                                                                                                                              
              database: main_development                                                                                                                                                    
              pool: 5                                                                                                                                                                       
              username: root                                                                                                                                                                
              password:                                                                                                                                                                     
              socket: /var/run/mysqld/mysqld.sock                                                                                                                                           

            test:                                                                                                                                                                           
              adapter: mysql2                                                                                                                                                               
              encoding: utf8                                                                                                                                                                
              reconnect: false                                                                                                                                                              
              database: main_test                                                                                                                                                    
              pool: 5                                                                                                                                                                       
              username: root                                                                                                                                                                
              password:                                                                                                                                                                     
              socket: /var/run/mysqld/mysqld.sock  

            production:                                                                                                                                                                           
              adapter: mysql2                                                                                                                                                               
              encoding: utf8                                                                                                                                                                
              reconnect: false                                                                                                                                                              
              database: main_prod                                                                                                                                                    
              pool: 5                                                                                                                                                                       
              username: root                                                                                                                                                                
              password:                                                                                                                                                                     
              socket: /var/run/mysqld/mysqld.sock 

    another_database:
                adapter: "mysql2",                                                                                                                                                       
                encoding: "utf8",                                                                                                                                                        
                reconnect: false,                                                                                                                                                        
                database: "peripheral",                                                                                                                                                 
                pool: 5,                                                                                                                                                                 
                username: "root",                                                                                                                                                        
                password: "",                                                                                                                                                            
                socket: "/var/run/mysqld/mysqld.sock"



Now In Migration file specify:
ActiveRecord::Base.establish_connection(:another_database)


class CreateRetailerToDomains < ActiveRecord::Migration
ActiveRecord::Base.establish_connection(:another_database)
 def change                                                                                                                                                                    
     create_table :retailer_to_domains do |t|                                                                                            
          t.string :name                                                                                                                                                            
          t.string :domain                                                                                                                                                          

          t.timestamps                                                                                                                                                              
        end                                                                                                                                                                         
      end                                                                                                                                                                           
    end  



 It will get create table inside that database only.


Model

class RetailerToDomain < ActiveRecord::Base
  ActiveRecord::Base.establish_connection(:another_database)
end


**To check the active database connection**
ActiveRecord::Base.connection.current_database
Pompano answered 27/9, 2012 at 6:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.