LoginSignup
70
72

More than 5 years have passed since last update.

インストールからRails-PostgreSQL環境を整える

Posted at

環境

$ psql --version
psql (PostgreSQL) 9.3.10

$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.3 LTS"

$ bundle list
  * pg (0.18.3)
  * rails (4.2.4)
  ...

PostgreSQLの設定

$ sudo apt-get install postgresql
# installするとPostgreSQLのサービスがバックで走る
$ /etc/init.d/postgresql status
9.3/main (port 5432): online
# PostgreSQLのroot userであるpostgresユーザとしてpsqlを実行する
$ sudo -u postgres psql

これから設定するrailsプロジェクトのロールを準備します。

postgres=# create role projectname with createdb login password 'password';
postgres=# \q

Railsの設定

$ rails new projectname -TB --database=postgresql
$ cd projectname

このままbundle installするとpgがエラーとなるので、依存関係をインストールしておきます。

$ sudo apt-get install libpq-dev

必要なgemをインストールします。

Gemfile
source 'https://rubygems.org'

gem 'rails', '4.2.4'
gem 'pg'

# scaffold確認用に必要
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
$ bundle install --path vendor/bundle

railsと先ほど作ったPostgreSQLのロールを関連付ける為、config/database.ymlを編集します。

config/database.yml
default:
  adapter: postgresql
  encoding: unicode
  pool: 5
  # 以下の3つを追加
  username: projectname
  password: password
  # RailsサーバとPostgreSQLサーバが同じ場合
  host: localhost
development:
  <<: *default
  database: projectname_development
test:
  <<: *default
  database: projectname_test

rake db:setupに必要なdb/schema.rbを生成します。

$ rake db:migrate

その後に、projectname_developmentprojectname_testという名前のデータベースを作成します。

$ rake db:setup

データベースを利用してみましょう。

$ rails g scaffold Post title:string body:text
$ rake db:migrate
$ rails s

準備ができたので、localhost:3000/postsにブラウザでアクセスして動作を確かめてみてください。

参考

70
72
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
70
72