Toyアプリケーション(Vagrant + CentOS7 + Rails 5.1.6です)
centos側
$ cd ディレクトリ移動
$ rails _5.1.6_ new toy_app
Toyアプリケーション用にgemファイルの修正(リスト2.1)
$ bundle install --without production
Bundler could not find compatible versions for gem “activesupport”:
In snapshot (Gemfile.lock):
activesupport (= 5.1.6.2)
省略….
Running bundle update will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.
エラーでてたので、
$ bundle update
gitで管理下に
$ git init
$ git add -A
$ git commit -m "Initialize repository"
==bitbucketでrepositoryを作成
$ git remote add origin git@bitbucket.org:USERNAME/toy_app.git
$ git push -u origin master
文字表示できるか確認コントローラーとルーティングの設定
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def hello
render html: "hello world"
end
end
config/routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'application#hello'
end
変更をコミットしてHerokuにpush
$ git commit -am "Add hello"
$ heroku create
$ heroku rename 名前
$ git push heroku master
ユーザモデルとポスト(マイクロポスト)のモデルを設計する
ユーザ(users)id(integer), name(string), email(string)のテーブルをつくる
ポスト(microposts)id(integer), content(text), user_id(integer)
scaffoldで生成
$ rails generate scaffold User name:string email:string
(id は自動で主キーとして追加されるため、追加不要)
データベースのマイグレート
$ rails db:migrate
ユーザーページでユーザを追加してみる
http://rails-toy.vagrant.test/users
[URL][アクション][用途]
/users index (ユーザ一覧)
/users/1 show(ユーザの詳細)
/users/new new(新規ユーザ追加)
/users/1/edit edit (ユーザの編集)
ルーティングを修正して、rootでUserの一覧を表示
routes.rb
root 'users#index'
# root 'application#hello'
マイクロポストを生成する
$ rails generate scaffold Micropost content:text user_id:integer
$ rails db:migrate
ポストを追加してみる
ポストの文字数制限をする
app/models/micropost.rb
class Micropost < ApplicationRecord
validates :content, length: { maximum: 140 }
end
あれ、validatesが効かずにpostできてしまう。(未解決)
ユーザとマイクロポストの関連付け
app/models/user.rb
class User < ApplicationRecord
has_many :microposts
end
app/models/micropost.rb
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length: { maximum: 140 }
end
デプロイ
$ git status
$ git add -A
$ git commit -m "Fin toy app"
$ git push
$ git push heroku
$ heroku run rails db:migrate
$ heroku open