我想比我的database.yml文件中定义的另一个数据库中创建一个新表。
这是我的database.yml文件:
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
我有所谓的“外围”另一个数据库。 我想创建一个数据库名为“retailer_to_domain”里面的表。
这里是我的移民文件:
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
由命令生成的迁移文件: rails generate model RetailerToDomain name:string domain:string
,然后我加入def connection
方法从database.yml中配置覆盖默认数据库(“主”)。
当我运行迁移( rake db:migrate
)的retailer_to_domains表得到的main_development数据库中创建。 如何重写此默认获得迁移来创建表,我想呢?
此外,我预计RetailerToDomain模型来访问与establish_connection方法看起来像这样类似的方式该表:
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
在此先感谢这里的任何想法!