我想在我的 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 配置中覆盖默认数据库(“main”)的方法。
当我运行迁移 ( rake db:migrate
) 时,在 main_development 数据库中创建了retailer_to_domains 表。如何覆盖此默认值以使迁移在我想要的位置创建表?
另外,我希望 RetailerToDomain 模型以类似的方式访问此表,建立连接方法如下所示:
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
在此先感谢您的任何想法!