以下、API mode をサクッと初期構築するための手順メモです。
作りたいアプリのフォルダを用意する。
$ mkdir sample_api_app
$ cd sample_api_app
Rails5 ではバージョン2.2.2以上の Ruby が必要なので、rbenv などでバージョンを変更する。
(今回 rbenv のインストール方法については記載しません)
$ rbenv install -v 2.3.3
$ rbenv local 2.3.3
$ ruby -v # バージョンを確認
Gemfile を生成する。
$ gem install bundler
$ bundle init
Gemfile にある Rails の記載をコメントアウトし、バージョンを 5 にする。
$ vi Gemfile
↓↓↓
Gemfile
# A sample Gemfile
source "https://rubygems.org"
# Comment out and set version
gem "rails", "~> 5.0"
Rails をインストールし、API mode で初期構築する。
(rails new 時に --api
をつけるだけです)
$ bundle install --path vendor/bundle
$ bundle exec rails new . --skip-bundle --api # すべてYでよい
$ bundle update
User の CRUD を作成する。
$ bundle exec rails g scaffold User name:string age:integer
$ bundle exec rake db:create
$ bundle exec rake db:migrate
Rails サーバーを起動する。起動はやい。
$ bundle exec rails s
=> Booting Puma
=> Rails 5.0.0.1 application starting in development on http://localhost:3000
# frozen_string_literal: true
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.6.2 (ruby 2.3.3-p222), codename: Sleepy Sunday Serenity
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
curl で疎通テストをしてみる。
$ curl http://localhost:3000/users
[]%
$ curl http://localhost:3000/users -X POST -d 'user[name]=shibukk&user[age]=76'
$ curl http://localhost:3000/users
{"id":1,"name":"shibukk","age":76,"created_at":"2016-12-13T01:55:15.528Z","updated_at":"2016-12-13T01:55:15.528Z"}%
いけました