LoginSignup
11
11

More than 5 years have passed since last update.

Rails5で初めてのPostgreSQLを使うときの手順とエラー解消方法[メモ]

Last updated at Posted at 2018-05-23

参考:インストールからRails-PostgreSQL環境を整える
参考:RailsでPostgreSQLの情報を確認する
参考:rails側のエラー
参考:Railsアプリケーションを作ろう:PostgresからScaffold

結構時間がかかったが、これで何とかなった。
Rails5の構築にも慣れてきて、SQLiteからPostgreSQLへ変更して、「さてHerokuでも接続するか」で躓いたところ。

確認事項

まずOS(Ubuntu)にPostgres入ってないから。
なのでインストールする。

入っているか入っていないのかは

$ psql --version

このコマンドで確認できる。

$ sudo apt-get install postgresql
$ /etc/init.d/postgresql status
$ sudo -u postgres psql
postgres=# create role projectname with createdb login password 'password';
postgres=# \q

\qで退出できる。忘れると消さないといけないので忘れない様に。
だいたい.q だの\q だの quit なので覚えておく様に。

$ rails new mymemo -TB --database=postgresql
$ cd mymemo 
$ sudo apt-get install libpq-dev
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
$ bundle install
config/database.yml
default:
  adapter: postgresql
  encoding: unicode
  pool: 5
  # 3つを追加
  username: mymemo
  password: password
  host: localhost
$ rake db:migrate

ここでエラーが出た。

何度か消したりやり直したりしたせいの様だ。

PG::DuplicateTable: ERROR:  relation "memos" already exists
ActiveRecord::StatementInvalid: PG::DuplicateTable: ERROR:  relation "memos" already exists

簡単に翻訳すると既に memos テーブルあるよってこと。

簡単な方法(追記)

$ rails db:migrate:reset

テーブルの削除とマイグレーションを一緒にやってくれるコマンド。
これで一発解消。

ここからPostresqlのテーブルを消す(旧方法)

Postgresqlに入って修正する方法

$ rails dbconsole

Postgresに入る。
\l のコマンドで一覧を表示

mymemo_development=> \l

で該当するテーブルを削除する

mymemo_development=> drop table memos;
\q
$ rake db:migrate
== 20180523015057 CreateMemos: migrating ======================================
-- create_table(:memos)
   -> 0.0133s

これでもう一回データベースをマイグレートしてOK。

$ rails s

でサーバー起動して確認。
無事動いている!

rails sで起動しないとき

$ rails s -b 192.168.xxx.xxx 

IPアドレスを打つと起動できます。
「-d」じゃなくて「-b」だから。

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11