Cloud9 - Rails |将数据库从 SQLite3 更改为 PostgreSQL

Cloud9 - Rails | Change database from SQLite3 to PostgreSQL

我正在使用 ruby 2.3.0p0, Rails 4.2.4cloud 9 上,我想将我的数据库从 SQLite3 更改为 PostgreSQL。

我有一些关于sqlite3的资料。

# config/database.yml
default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3
test:
  <<: *default
  database: db/test.sqlite3
production:
  <<: *default
  database: db/production.sqlite3

我尝试了 taps gem,它要求输入用户名和密码,但我不知道在哪里可以找到这些凭据。

这个问题还有其他解决办法吗?

您的 database.yml 文件应该类似于 postgres:

default: &default
  adapter: postgresql
  user: username
  password: *****
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: myrubyblogdev

test:
  <<: *default
  database: myrubyblogtest

此外,在 gemfile 中添加 gem 'pg'

对于sqlite数据库中包含的数据,您可以创建一个rake任务将数据传输到您新建的postgres数据库中。

首先你要检查postgresql是运行ning,如果你必须启动它那么运行:

$ sudo service postgresql start

进入交互式postgresql终端psql:

$ sudo sudo -u postgres psql

创建一个用户并提供其密码,然后退出 psql:

postgres=# CREATE USER username SUPERUSER PASSWORD 'password';
postgres=# \q

创建环境变量以将它们放入您的 config.yml 文件,将它们导出到 ~/.profile 文件:

$ echo "export USERNAME=username" >> ~/.profile
$ echo "export PASSWORD=password" >> ~/.profile

然后从 postgresql 更新 template1:

$ sudo sudo -u postgres psql
postgres# UPDATE pg_database SET datistemplate = FALSE WHERE datname = 'template1';
postgres# DROP DATABASE template1;
postgres# CREATE DATABASE template1 WITH TEMPLATE = template0 ENCODING = 'UNICODE';
postgres# UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template1';
postgres# \c template1

收集垃圾并分析数据库运行宁VACUUM:

postgres# VACUUM FREEZE;
postgres# \q

现在更新您的配置文件,使其内容与您之前所做的一致:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: <%= ENV['USERNAME'] %>
  password: <%= ENV['PASSWORD'] %>
  host:     <%= ENV['IP'] %>

development:
  <<: *default
  database: app_development

test:
  <<: *default
  database: app_test

production:
  <<: *default
  database: app_production

检查您是否安装了 pg gem,如果没有则 运行,然后将其添加到您的 Gemfile 中并捆绑它:

gem install pg
bundle install

如果您的数据库仍未创建 and/or 您会收到以下消息:

ActiveRecord::NoDatabaseError: FATAL:  database "<project_name>_development" does not exist

然后运行创建它的适当命令:

rake db:create

要测试是否一切正常 运行,请尝试生成一个简单的脚手架:

rails g scaffold Post title content:text

要将此迁移及其内容持久保存到数据库,运行 迁移命令:

rake db:migrate

现在,如果你已经成功,一切都应该没有问题,你可以 运行:

rails console

在数据库中创建一条新记录:

Post.create title: 'Number one', content: 'Lorem Ipsum' 

并继续编码并享受乐趣。

注意:如果您遇到过如下错误:

PG::ConnectionBad: fe_sendauth: no password supplied

然后检查你的env变量是否正常,如果错误仍然存​​在你可以'hardcode'文件名和密码到config.yml文件,虽然不推荐这样做,所以,最好在最坏的情况下,你尽量避免这种情况 'solution'。