Rails:SQLiteをやめてPostgreSQLを使う

1. まずはPostgreSQLをインストール

インストールする

$ brew install postgresql

DBを初期化する

$ initdb /usr/local/var/postgres

サーバを起動する

$ pg_ctl start -D /usr/local/var/postgres

接続してみる

$ psql
psql: could not connect to server: Permission denied
    Is the server running locally and accepting
    connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

確認する

$ psql -l

以下のような感じで出れば成功。

                                   List of databases
        Name         | Owner     | Encoding |   Collate   |    Ctype    | Access privileges
---------------------+-----------+----------+-------------+-------------+-----------------------
 postgres            | yourname  | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 |
 template0           | yourname  | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/yourname          +
                     |           |          |             |             | yourname=CTc/yourname
 template1           | yourname  | UTF8     | ja_JP.UTF-8 | ja_JP.UTF-8 | =c/yourname          +
                     |           |          |             |             | yourname=CTc/yourname

2. gemを入れる

$ gem install pg
$ bundle install

3. config/database.ymlを書き換える

development:
  adapter: postgresql
  encoding: utf8
  database: project_development
  pool: 5
  username:
  password:

test: &TEST
  adapter: postgresql
  encoding: utf8
  database: project_test
  pool: 5
  username:
  password:

production:
  adapter: postgresql
  encoding: utf8
  database: project_production
  pool: 5
  username:
  password:

cucumber:
  <<: *TEST

各DBのconfig/database.ymlの設定は以下の通り。

SQLite

MySQL

PostgreSQL

4. データベースを初期化する

$ rake db:create
$ rake db:migrate

以上で完了。

RailsのデフォルトのDBはSQLiteなので、DBを指定する場合は、

$ rails new MyApp -d postgresql
$ rails new MyApp -d mysql

とする。