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!