Rails4をherokuにdeployする

Posted by Tatsuyano on Thu, Feb 19, 2015
In
Tags ruby, heroku, rails

備忘のため、Rails4をheroku上にdeployする方法をメモしておきます。

herokuのアカウントの作成、及び鍵の設定は終っているものとします。

$ ruby  -v 2.2.0p0
$ rails -v 4.2.0

## サンプルアプリの作成 まずはherokuにdeployするアプリを生成
$ rails new heroku-rails
$ cd heroku-rails

herokuではsqlite3はサポートされていないので、productionからは外すようにする。今回productionで使うDBは、heroku標準のpostgressを選択。 また、Rail4から`rails_12factor`が必須になったらしいので設定。 Gemfile
group :development do
  gem 'sqlite3'
end
group :production do
  gem 'pg'
  gem 'rails_12factor'
end

開発環境では、postgressを使っていないので、`--without production`をつけて productionでのみ必要なGemは開発環境には入れないようにする。
$ bundle install --without production

開発環境でも`pg`を使う場合は、以下のようにpostgress本体と、develをインストールする。
$ sudo yum install -y postgresql-devel
$ sudo yum install -y postgresql
$ gem install pg

ここまでで空のアプリができたので、いったん`git commit`。
$ git init
$ git add .
$ git commit -m 'initial commit'

次にherokuにログインし、`heroku create`してheroku上にアプリを生成する。 この時、アプリ名を指定しなければ、適当な名前で生成される(後から変更可)。 *アプリ名はURLに含まれるため、heroku全体でユニークである必要がある*
$ heroku login
$ heroku create <アプリ名>
$ git push heroku master  # この段階でheroku上にdeployされる。

ちなみに`git commit`する前に`heroku create`すると、herokuのremote-urlが設定されないので、 その場合は、自分で設定する必要がある。
$ git remote set-url heroku  https://git.heroku.com/<アプリ名>.git

アプリの情報は、`heroku app:info`で確認ができる。
$ heroku apps:info
=== fast-stream-xxxx
Addons:        heroku-postgresql:hobby-dev
Dynos:         1
Git URL:       https://git.heroku.com/fast-stream-xxxx.git
Owner Email:   xxxxxx@xxxx.com
Region:        us
Repo Size:     24k
Slug Size:     27M
Stack:         cedar-14
Web URL:       https://fast-stream-xxxx.herokuapp.com/
Workers:       0

しかし、作成したアプリのURLをたたくと、以下のようなエラーが出る。 ![](https://dl.dropboxusercontent.com/u/159938/blog_images/deploy-the-rails4-to-heroku_01.png) heroku上のアプリでは、いつものRailsのTOP画面は出てこない。 ここまでの状態で、heroku上で動いているのを確認したい場合は、 仮のTOPページを生成してgit commitし、再度`heroku push origin master`してdeployすると確認できる。
$ cat >> public/index.html
index.html

## herokuでDBを使う  `scaffold`で、DBにアクセスする機能を実装してみる。 開発環境で、`rake db:migrate`した場合は、herokuでも`migrate`する必要がある。
$ rails g scaffold Book title:string price:integer
$ rake db:migrate
$ git add .
$ git commit -m 'rails g scaffold Book title:string price:integer'

$ git push heroku master
$ heroku run rake db:migrate # <= This!

TwitterBootStrapのGlyphiconを使う

BootStrapのGlyphiconを使ったアプリをherokuにdeployしても、そのままでは使えない。 使うためには、production環境(heroku)でも、assets.compileを有効にする必要がある。

config/environments/production.rb

#config.assets.compile = false
 config.assets.compile = true

参考サイト