Rails:如何在开发过程中将我的数据库从SQLite更改为PG?

时间:2012-12-24 18:09:14

标签: ruby-on-rails postgresql

我使用默认的SQLite数据库生成了我的rails应用程序,但在创建了几个模型并迁移几次后,我想将其更改为Postgresql。

我将postgres gem添加到我的Gemfile,bundle install,然后我替换了所有的database.yml代码

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5
  username: postgres
  password: mypass

development:
  <<: *default
  database: sample_app_development

test:
  <<: *default
  database: sample_app_test

production:
  <<: *default
  database: sample_app_production

即使密码正确,我也会收到FATAL: password authentication failed for user "postgres"错误。是因为我错过了一步吗?我是否应该告诉PG使用pg Admin III,我想将此应用程序添加到我的服务器?我应该创建一个新的角色/连接吗?

我遇到过这个问题几次,似乎无法找到这个特定问题的答案。

当我尝试运行rake db:drop时,它会给我这个:

Couldn't drop sample_app_development : #<PGError: FATAL:  role "postgres" does not exist
>
Couldn't drop sample_app_test : #<PGError: FATAL:  role "postgres" does not exist
>

======

Edmunds-MacBook-Pro:sample_app edmundmai$ createuser foo
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) y
Password: 
createuser: could not connect to database postgres: FATAL:  password authentication failed for user "edmundmai"

3 个答案:

答案 0 :(得分:2)

Postgres用户身份验证有点奇怪。默认设置是使用与操作系统相同的身份验证(至少在Linux中)。因此,要从命令行获取Postgres提示,您必须执行以下操作:

sudo -u postgres psql

请注意,没有密码 - 并且由于操作系统负责身份验证,因此不需要密码(如果需要,操作系统会询问您的sudo密码)。

所以选择一个就是从你的Rails配置文件中删除密码选项,希望一切顺利。如果做不到这一点,请通过编辑pg_hba.conf文件(我在/etc/postgresql/9.2/main/pg_hba.conf处)来设置Postgres以接受基于密码的身份验证。这是我本地服务器的一个例子;用户“postgres”使用操作系统的身份验证(“peer”),但用户“opengeo”使用密码(“md5”):

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   all             postgres                                peer
local   all             opengeo                                 md5

希望有所帮助!

答案 1 :(得分:1)

要将数据库转换为postgresql,请首先按以下方式创建用户:

$ createuser foo
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) y

创建数据库:

CREATE DATABASE foo_db ENCODING 'UTF8' OWNER foo;

确保您的database.yml如下所示:

development:
  adapter: postgresql
  encoding: unicode
  database: foo_db
  pool: 5
  username: foo
  password:

test:
  adapter: postgresql
  encoding: unicode
  database: foo_test
  pool: 5
  username: foo
  password:

答案 2 :(得分:0)

development:
  adapter: postgresql
  database: postgres
  username: postgres
  password: ;ernakulam
  pool: 5
  timeout: 5000

test:
  adapter: postgresql
  database: postgres
  pool: 5
  timeout: 5000

production:
  adapter: postgresql
  database: postgres
  pool: 5
  timeout: 5000`