ミニQ&Aアプリを作ろう!
開発環境はCloud9で行う
0:ソフトウェアのアップデートをします。
sudo yum update
Rubyのバージョン確認
rvm -v rvm install 2.5.1 rvm install 2.6.4 rvm list ruby2.5.1を使う rvm use 2.5.1 バージョン確認 ruby -v 2.5.1をデフォで使いたいとき rvm --default use 2.5.1 rvm list
1:まず新規プロジェクトの作成
cd ~/environment/rails_projects ls rails -v ruby -v rails _5.2.1_ new qa
エラーを回避するためにgemfileのsqlite3の部分を追加↓
gem 'sqlite3', '~> 1.3.6' # ~/environment/rails_projects/helloにいることを確認しsqlite3をアプデ bundle update
2:データベースを作成する
rails db:create レイルズサーバー起動 rails s
localhostで↓のようなものが確認できればOK

3:コントローラーを作成 MVCのC
#questionsというコントローラー↓を作成 rails g controller questions index show new edit #保有するアクション↑ indexは質問の一覧表示 showは詳細確認 newは新規作成 editは編集担当
app/controller/questions_controllerで
↓のようにそれぞれのアクションができている!!
class QuestionsController < ApplicationController def index end def show end def new end def edit end end
更にapp/views/questionsの中に
edit.html.erb, index.html.erb, new.html.erb, show.html.erb
が作成されているのを確認します。
4:questionモデルの作成 MVCのM
questionという名↓のモデルを作成 ↓データ・ベースのカラムの情報の定義
rails g model question name:string title:string content:text
name:投稿者の名前をstring型 :質問のタイトルをstring型 質問の本文をtext型にしている
db/migrate/20210103のところにいく
上記の設定が反映されています。
class CreateQuestions < ActiveRecord::Migration[5.2]
  def change
    create_table :questions do |t|
      t.string :name
      t.string :title
      t.text :content
      t.timestamps
    end
  end
end
スペルミスがないか注意すること!!
5:データベースに送る(マイグレート)
rails db:migrate
ターミナルで確認します。
rails dbconsole
.schema
↓のようになっていればOK
CREATE TABLE "questions" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar, "title" varchar, "content" text, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
.qで戻る
rails s でサーバー起動してURLにアクセス↓
Questions#index
Find me in app/views/questions/index.html.erb

このようになっていればOK
↑はapp/views/questions/index.html.erbの内容を表示しているよ
6:ルーティングの設定
rails routes questions_index GET /questions/index(.:format) questions#index ↑/questions/indexでアクセスしたときquestionsコントローラーの indexアクションをするということ
config/routes.rbにて
Rails.application.routes.draw do # get 'questions/index' # get 'questions/show' # get 'questions/new' # get 'questions/edit' resources :questions # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
コメントアウトしているところは自動生成されたもので
一般的なアプリケーションに必要なルーティングを自動で用意してくれます。
resourcesメソッドを使うと(複数形であることに注意)
questions_controllerに関係するルーティングを自動で用意してくれます。
rails routesで確認
  Prefix      Verb   URI Pattern       Controller#Action
questions     GET /questions(.:format)          questions#index
             POST /questions(.:format)         questions#create
new_question  GET /questions/new(.:format)      questions#new
edit_question GET /questions/:id/edit(.:format) questions#edit
question      GET /questions/:id(.:format) questions#show
            PATCH /questions/:id(.:format) questions#update
              PUT /questions/:id(.:format) questions#update
           DELETE /questions/:id(.:format) questions#destroy
rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update
rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
index:     質問一覧
create: 質問の新規作成のときの処理
new:        質問の新規登録画面
edit:        質問の編集画面
show:      質問詳細確認画面
update:   質問の内容を更新するときの処理
destroy:  質問の削除
Prefixはパスを指定するのに使います。
Verb:HTTPメソッドとかHTTPリクエストメソッドとも呼ばれます。
Get        データの取得 PUT
POST     データの送信
DELETE データの削除
URI Pattern いわゆるアドレスです。
questionsコントローラーのindexアクションを実行するには
/questions/indexでアクセスすればよいということで
↑のものはconfig→routes.rbで変えることができます。
7:rootメソッドの設定
これからやること
ルートURLでアクセスしたとき質問の一覧が表示されるようにしたい
config/routes.rbにて記述↓
  Rails.application.routes.draw do 
    root 'questions#index' 
    resources :questions
end
ルートURLにアクセスしたときquestionsコントローラーのindexアクションを
呼ぶ設定をしました。
ルートURLでアクセスしたとき↓が表示されます。
Questions#index
Find me in app/views/questions/index.html.erb
rails routesで↓のようになっていればOKです。
root GET / questions#index
ルートURLにアクセスしたときquestionsコントローラーのindexアクションを呼ぶ設定をしました。
8:質問の一覧ページの作成
app/controllers/questions_controllerにて設定↓
class QuestionsController < ApplicationController
  def index
 #questionsテーブルからすべての質問を取得する
    @questions = Question.all
  end
  def show
  end
  def new
  end
  def edit
  end
app/views/index.html.erbにて↓のように記述
<h2>Questions#index</h2>
  <div class="row">
  <div class="col-md-12">
    <table class="table table-striped">
     <thead class="thead-light">
       <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Menu</th>
       </tr>
     </thead>
    </table>
  </div>
</div>
ブラウザから/questionsにて↓のようになってればOK
Questions#index
ID Title Menu

更に次のように記述
<h2>Questions#index</h2>
  <div class="row">
  <div class="col-md-12">
    <table class="table table-striped">
     <thead class="thead-light">
      <tr>
       <th>ID</th>
       <th>Title</th>
       <th>Menu</th>
      </tr>
     </thead>
   <tbody>
    <% @questions.each do |question| %>
     <tr>
      <td><%= question.id %></td>
      <td><%= question.title %></td>
      <td>[edit] [Delete]</td>
     </tr>
    <% end %>
   </tbody>
  </table>
</div>
app/controllers/questions_controllerにて
@questions = Question.all
Questionテーブルから全てのデータを取り出して
@questionsに代入して
app/views/questions/index.html.erbの中で使われます。
具体的には複数入っているquestionのデータをeachで一つずつ取り出して、
question,idやタイトルを質問回数分表示しています。
9:シードファイルを使った初期データの投入
質問を投稿する機能が未実装で、
一覧画面データが表示されているところの動作確認ができないので
初期データを作ってデータベースへ挿入、
シードファイルを使った初期データの投入する機能を使います。
db/seeds.rbで↓のように記述して初期データの投入をします。
Question.create(id: 1, name: 'test name 1', title: 'Test question 1', content: 'Test content 1') Question.create(id: 2, name: 'test name 2', title: 'Test question 2', content: 'Test content 2') Question.create(id: 3, name: 'test name 3', title: 'Test question 3', content: 'Test content 3')
Question.createで3レコード分のデータを作り
ターミナルにて↓のようにコマンド rails db:seed
何も表示されなければOK
ルートURLでアクセスしたとき↓のように表示されればOK
Questions#index ID Title Menu 1 Test question 1 [edit] [Delete] 2 Test question 2 [edit] [Delete] 3 Test question 3 [edit] [Delete]

10:Bootstrapを導入する(フロントの部分を効率良く使う)
Gemfileにて一番下に次を記述します。
gem 'bootstrap', '~> 4.1.1' gem 'jquery-rails', '~> 4.3.1'
ターミナルにてbundle installでインストール ターミナルにて↓のようにしてリネーム(拡張子cssをscss)に変更 mv app/assets/stylesheets//application.css app/assets/stylesheets/application.scss
scssはサスを記述するためのファイルの拡張子でCSSを便利に実装するためのスクリプト言語です。
原則cssを記述、プロジェクト全体で使われるスタイルを記述するためのファイル
app/assets/stylesheets/application.scssを開き記述
bootstrapを読み込む設定 @import "bootstrap";
app/assets/javascripts/application.jsにて↓のように記述
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's // vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require rails-ujs //= require activestorage //= require turbolinks //= require jquery3 //= require popper //= require bootstrap-sprockets //= require_tree .
セーブしてルートURLでアクセスしたときスタイルが当たっていればOKです。
レイアウトを中央揃えにしたいので
app/views/layouts/application.html.erbにて↓のように記述します。
<!DOCTYPE html>
<html>
<head>
  <title>Qanda</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
  <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
  <div class="container">
    <%= yield %>
  </div>
 </body>
</html>
yieldはindex.html.erbなどの各ページごとに異なる実装が呼び出されて、埋め込まれる

上のように中央揃えになったのを確認します。
ページのソースを表示から<h2>タグから
<h2>Questions#index</h2>
  <div class="row">
  <div class="col-md-12">
    <table class="table table-striped">
      <thead class="thead-light">
     <tr>
      <th>ID</th>
      <th>Title</th>
      <th>Menu</th>
     </tr>
      </thead>
    <tbody>
     <tr>
      <td>1</td>
       <td>Test question 1</td>
       <td>[edit] [Delete]</td>
      </tr>
     <tr>
      <td>2</td>
       <td>Test question 2</td>
       <td>[edit] [Delete]</td>
     </tr>
     <tr>
      <td>3</td>
      <td>Test question 3</td>
      <td>[edit] [Delete]</td>
     </tr>
    </tbody>
   </table>
 </div>
</div>
ここまではapp/views/questions/index.html.erbで書かれた部分
他の部分はapp/views/layouts/application.html.erbで書かれた部分でこの2つが合わさってページが表示されている。

