2

我需要使用 postgresql db 将一些旧数据从 sqlite3 db 导入到我的 rails 应用程序中。所以我用遗留 sqlite3 db 的所有列类型创建了一个模型“businesses”。我更改了 database.yml 文件等......在模型 business.rb 我添加了这一行:

class Business < ActiveRecord::Base

establish_connection "citylistings_development"
end

这使我能够连接到 sqlite3 db,并创建了一个 index.html.erb 文件,我可以在浏览器中看到其中的内容。

在控制器中,我的代码是这样的:

class BusinessesController < ApplicationController
def get_all
  @businesses = Business.all
end

def create_db_entries
 self.get_all
end

def index
respond_to do |format|
  format.html #index.html.erb

end
end
end

现在我注意到,当我创建模型“business.rb”时,它在我的 postgresql 数据库中创建了表。

但是,很明显它从我的 sqlite3 数据库中读取数据,因为它连接到该数据库。

我的问题是这样的

如何将其输出到 index.html.erb 文件的数据写入 pg db?这甚至可能吗?

模型实例可以一次连接到 2 个数据库并从 1 读取并写入另一个吗?

我知道解决这个问题的一种方法是创建另一个模型“tempbiz”,它将条目写入 pg 数据库,而“业务”模型从 sqlite3 数据库读取。我想知道“商业”模型是否可以同时完成这两项任务?

谢谢


编辑这是我的 database.yml 根据下面的评论(我排除了所有被注释掉的东西)

#===============================================================================
development:
 adapter: postgresql
 encoding: unicode
 database: XXX_development
 pool: 5
 username: XXX
 password: XXXX
#===============================================================================
citylistings_development:
 adapter: sqlite3
 database: db/citylistings.sqlite3
 pool: 5
 timeout: 5000
4

2 回答 2

1

我看到了有关此主题的演示文稿,您需要查看 secondbase gem。引用它的文档“SecondBase 为您的应用程序添加了第二个数据库。虽然 Rails 允许您建立与任意数量的外部数据库的连接,但 Rails 只能管理单个数据库及其迁移和测试任务。”

https://github.com/karledurante/secondbase

It was created for the exact reason you need it. They had a legacy database that they needed to import.

Cheers, Sean

于 2012-05-03T15:07:49.213 回答
0

This will be native in Rails 6.

class AnimalsBase < ApplicationRecord
  connects_to database: { writing: :animals, reading: :animals_replica }
end

Here's the PR that introduced it.

于 2019-04-02T19:35:01.500 回答