Toyアプリケーション

WED(WeekEndDevelopers)のぽんたです。

開発スキルのないSIerからソフトウェアスキルを取得するため、WEDでモノづくりを計画しています。詳しい経緯はここ
※現在はruby on railsチュートリアル(ここから)を進めていってます。

今回から第2章に入っていきます。
この章では、Railsの強力な機能をいくつか学ぶためにおもちゃアプリケーションを作成します。

◆いつものようにrails newする

~/develop_environment$ rails new toy_app

◆Gemfileの編集

HerokuではSQLiteがサポートされていないため、sqlite3 gemが本番環境に導入されないようにしておきます。 編集した箇所にはコメント入れてます。

$ cat Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.4.1'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.3'
# Use sqlite3 as the database for Active Record
#gem 'sqlite3'  #***ponta add
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'sqlite3' #★ ponta追加
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of chromedriver to run system tests with Chrome
  gem 'chromedriver-helper'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

group :production do #★ponta追加
  gem 'pg'          #★ponta追加
end                  #★ponta追加

◆gemをインストール

--without productionオプションを追加することで、本番用のgemを除いたローカルgemのインストールができる(これも前回の復習のようなものですね^^)

$ bundle install --without production

◆GitでこのToyアプリケーションをバージョン管理下に置く

$ git init
$ git add -A
$ git commit -m "Initialize repository"

GitHubリポジトリを作成して関連付けしてpushする

GitHubの自分のページでリポジトリを作成して、pushします。 GitHubリポジトリの作成方法はこちら

$ git remote add origin https://github.com/<秘密>/toy_app.git

◆Applicationコントローラにhelloアクションを追加する

$ cat app/controllers/application_controller.rb 
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def hello
    render html: "hello, world!"
  end
end

◆ルートルーティングを設定する

$ cat 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にプッシュします

$ git commit -am "Add hello"
$ heroku create
$ git push heroku master

ここで前回実施したハロワと同等の骨組みが完成。

◆Usersリソースについて

UsersリソースをRailsプロジェクトに標準装備されているscaffoldジェネレータで生成します。
この機能がrailsアプリを作る上で非常に便利になるそうです。
本章ではそこまで深い理解はいらないとのことですが、なるべく理解して進めていきます。

scaffoldのコマンドの書式は次のようになるそうです。
実際やってみましょう。

$ rails generate scaffold モデル名 カラム名1:データ型1 カラム名2:データ型 2 …

rails generate scaffoldの実行

name:stringとemail:stringを指定してみた

$ rails generate scaffold User name:string email:stringRunning via Spring preloader in process 832
      invoke  active_record
      create    db/migrate/20190706135129_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      invoke  resource_route
       route    resources :users
      invoke  scaffold_controller
      create    app/controllers/users_controller.rb
      invoke    erb
      create      app/views/users
      create      app/views/users/index.html.erb
      create      app/views/users/edit.html.erb
      create      app/views/users/show.html.erb
      create      app/views/users/new.html.erb
      create      app/views/users/_form.html.erb
      invoke    test_unit
      create      test/controllers/users_controller_test.rb
      create      test/system/users_test.rb
      invoke    helper
      create      app/helpers/users_helper.rb
      invoke      test_unit
      invoke    jbuilder
      create      app/views/users/index.json.jbuilder
      create      app/views/users/show.json.jbuilder
      create      app/views/users/_user.json.jbuilder
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/users.coffee
      invoke    scss
      create      app/assets/stylesheets/users.scss
      invoke  scss
      create    app/assets/stylesheets/scaffolds.scss

これでユーザーリソースなるものが出来たわけですね!

◆データベースをマイグレードする

データベースを更新し、usersデータモデルを作成するためのものらしいです。

$ rails db:migrate
== 20190706135129 CreateUsers: migrating ======================================
-- create_table(:users)
   -> 0.0024s
== 20190706135129 CreateUsers: migrated (0.0026s) =============================

ここまでの手順が完了すると、"rails s"コマンドでローカルWebサーバーを別タブで実行できるようになります。今回はほぼ復習ばかりでしたが、長くなってしまったのでここまでにします。

次回はWebサーバーを別タブで実行したらどうなるのかを確認していきます!では^^