【第2章】オンライン教科書サービス作成【データの表示】
目的
第1章で作成したデータベースにテーブルを作成し、下図のようにデータを表示できるようにする。
ルーティング設定
config/routes.rb
を下記のように実装する。
Rails.application.routes.draw do root to: 'texts#index' end
コントローラー生成
コントローラーを生成するには、rails g controller <コントローラー名>
を実行する。
ターミナル
cd online_text
rails g controller texts
上記コマンド実行後、app/controllers/texts_controller.rb
が生成される。
生成されたコントローラーを下記のように実装する。
class TextsController < ApplicationController def index end end
モデル生成・マイグレーションファイルの編集
textsテーブルとやりとりするTextモデルを下記コマンドを実行して作成する。
ターミナル
cd online_text
rails g model text
上記コマンドを実行するとマイグレーションファイルが生成される。
DB設計書(ER図)に合わせて項目を追加する。
外部キーの項目に関しては対象テーブルが存在しない場合、エラーを発生するため、
対象テーブル生成後、外部キーを追加するマイグレーションファイルを作成する方針で進める。
db/migrate/20200914135559_create_texts.rb
class CreateTexts < ActiveRecord::Migration[5.2] def change create_table :texts do |t| t.string :title t.string :thumbnail t.string :abstract t.text :body, limit: 4294967295 t.integer :public_flag, null: false, default: 0 t.timestamps end end end
下記コマンドを実行してテーブルを作成する。
ターミナル
cd online_text
rails db:migrate
下図のようにSequel Proで生成したテーブルにアクセスし、対象のカラムが存在することを確認する。
仮データの導入
ビューで表示するための仮データをseeds.rb
を用いて登録する。
カラム:thumbnailについては画像投稿のgemを追加してからseeds.rb
を再度編集する。
db/seeds.rb
####################################### # テキストテーブルへのデータ登録 ####################################### p "create Texts" Text.create!( title: '集合と論理', # thumbnail: File.open("#{Rails.root}/db/fixtures/product1.jpeg"), abstract: '集合と倫理について理解する', body: '数学では、ある集まりのうち、さらに、それに属しているか属してないかを明確に区別できる条件のある物のあつまりを集合という。', public_flag: 1 ) Text.create!( title: '二次関数', # thumbnail: File.open("#{Rails.root}/db/fixtures/product1.jpeg"), abstract: '二次関数について理解する', body: '係数 a, b, c が実数値の定数で、x が実数値をとる変数とすると、そのグラフはxy-座標系において放物線を描く。', public_flag: 1 )
下記コマンドを実行してTextテーブルへ仮データを登録する。
ターミナル
cd online_text
rails db:seed
無事登録が完了するとテーブルが下図のようになる。
コントローラーへ追記
テキストからデータを取得できるようにコントローラーに下記記述を加える。
app/controllers/texts_controller.rb
class TextsController < ApplicationController def index @texts = Text.all end end
ビューファイルの実装
texts_controller
の@textsにはtextsテーブルの全レコードが格納されている。
@textsの情報をトップページへ表示するため、ビューファイルindex.html.erb
を作成し、実装を進める。
app/views/texts/index.html.erb
を作成し、下記のように記述する。
<% @texts.each do |text| %> <div class="content"> <div class="content__left"> <div class="content__left--image"></div> </div> <div class="content__right"> <div class="content__right__top"> <%= text.title %> </div> <div class="content__right__bottom"> <div class="content__right__bottom--date"> <%= text.abstract %><br> <%= text.body %> <br><br> </div> </div> </div> </div> <% end %>
下記のように表示されていれば成功
テンプレートの導入
アプリケーションのヘッダー部分は、トップ画面、投稿画面など画面遷移した先でも同じものを使用することが多い。
アプリケーションのビューファイルの共通部分をまとめて実装するのがレイアウトテンプレートと呼ばれるファイルである。
対象ファイルはapp/views/layouts/application.html.erb
であり、下記のように編集をする。
<!DOCTYPE html> <html> <head> <title>OnlineText</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> <header class="header"> <div class="header__Ïtitle"> <%= link_to "OnlineText", '#', class: "header__title--text" %> </div> <div class="header__right"> <%= link_to "新規テキスト作成", '#', class: "header__right--btn" %> </div> </header> <div class="contents"> <%= yield %> </div> </body> </html>
下記のように表示されれば成功です。
CSSの実装
レイアウトテンプレートの中に下記記述がある。
stylesheet_link_tag
上記は呼び出すCSSファイルの指定が可能になるメソッドである。
application
と記述されているため、このHTMLファイルからはapp/assets/stylesheets/application.css
というCSSファイルを読み込んでいることを表す。
app/assets/stylesheets/application.css
は下記のように記述されている。
/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's * vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS * files in this directory. Styles in this file should be added after the last require_* statement. * It is generally better to create a new file per style scope. * *= require_tree . *= require_self */
上記ファイルのrequire_tree .
はapp/assets/stylesheets
というディレクトリにあるCSSファイルやSCSSファイルを全て読み込むという記述である。
texts.scss
を下記のように記述する。
app/assets/stylesheets/texts.scss
body{ background-color: #f6f6f6; min-width: 650px; .header{ height: 56px; width: 100%; padding: 0 150px; background-color: #66FFCC; color: #fff; display: flex; justify-content: space-between; &__title{ font-size: 30px; line-height: 56px; &--text{ text-decoration: none; color: #fff; } } &__right{ &--btn{ text-decoration: none; line-height: 56px; color: #fff; margin-left:15px; } } } .contents{ margin: 30px auto 0; background-color: #fff; height: 600px; width: 70%; overflow: scroll; .content{ padding: 10px; border-bottom: 1px solid #f6f6f6; display: flex; &__left{ padding-right: 20px; &--image{ height: 55px; width: 55px; border: solid 1px; } } &__right{ width: calc(100%-100px); &__top{ font-size: 20px; font-weight: bold; &--title{ text-decoration: none; color: #000000; } } &__bottom{ font-size: 15px; color: #999; display: flex; &--userName{ &--btn{ text-decoration: none; color: #999; } } &--date{ margin-left: 20px; } } } &__title{ font-size: 30px; font-weight: bold; padding-top: 30px; text-align: center; } } .textTitle{ padding-top: 20px; text-align: center; font-size: 20px; font-weight: bold; } .textDate{ font-size: 15px; color: #999; text-align: center; } .textAuthor{ font-size: 15px; color: #999; text-align: center; } .textManage{ display: flex; justify-content: center; margin-top: 10px; &__edit{ display: block; border-radius: 5px; color: #ffffff; background-color:#66FFCC; padding: 0 10px; text-decoration: none; margin-right: 10px; } &__delete{ display: block; border-radius: 5px; color: #ffffff; background-color:#66FFCC; padding: 0 10px; text-decoration: none; margin-left: 10px; } } .textText{ margin: 20px 30px; } } .form{ width: 85%; height: 100%; margin: 0 auto; padding-top: 30px; &__title{ display: block; width: 100%; height: 50px; } &__text{ display: block; width: 100%; height: 50%; margin-top: 15px; } &__btn{ display: block; width: 30%; margin: 15px auto 0; } } .user{ padding: 15px 30px; } }
リセットCSSを配置
リセットCSSを下記のように記述し、ブラウザで表示内容を確認する。
app/assets/stylesheets/reset.scss
/*! normalize.css v2.1.3 | MIT License | git.io/normalize */ /* ========================================================================== * HTML5 display definitions * ========================================================================== */ /* * Correct `block` display not defined in IE 8/9. */ article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary { display: block; } /* * Correct `inline-block` display not defined in IE 8/9. */ audio, canvas, video { display: inline-block; } /* * Prevent modern browsers from displaying `audio` without controls. * Remove excess height in iOS 5 devices. */ audio:not([controls]) { display: none; height: 0; } /* * Address `[hidden]` styling not present in IE 8/9. * Hide the `template` element in IE, Safari, and Firefox < 22. */ [hidden], template { display: none; } /* ========================================================================== * Base * ========================================================================== */ /* * 1. Set default font family to sans-serif. * 2. Prevent iOS text size adjust after orientation change, without disabling * user zoom. */ html { font-family: sans-serif; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ } /* * Remove default margin. */ body { margin: 0; } /* ========================================================================== * Links * ========================================================================== */ /* * Remove the gray background color from active links in IE 10. */ a { background: transparent; } /* * Address `outline` inconsistency between Chrome and other browsers. */ a:focus { outline: thin dotted; } /* * Improve readability when focused and also mouse hovered in all browsers. */ a:active, a:hover { outline: 0; } /* ========================================================================== * Typography * ========================================================================== */ /* * Address variable `h1` font-size and margin within `section` and `article` * contexts in Firefox 4+, Safari 5, and Chrome. */ h1 { font-size: 2em; margin: 0.67em 0; } /* * Address styling not present in IE 8/9, Safari 5, and Chrome. */ abbr[title] { border-bottom: 1px dotted; } /* * Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome. */ b, strong { font-weight: bold; } /* * Address styling not present in Safari 5 and Chrome. */ dfn { font-style: italic; } /* * Address differences between Firefox and other browsers. */ hr { -moz-box-sizing: content-box; box-sizing: content-box; height: 0; } /* * Address styling not present in IE 8/9. */ mark { background: yellow; color: black; } /* * Correct font family set oddly in Safari 5 and Chrome. */ code, kbd, pre, samp { font-family: monospace, serif; font-size: 1em; } /* * Improve readability of pre-formatted text in all browsers. */ pre { white-space: pre-wrap; } /* * Set consistent quote types. */ q { quotes: "\201C" "\201D" "\2018" "\2019"; } /* * Address inconsistent and variable font size in all browsers. */ small { font-size: 80%; } /* * Prevent `sub` and `sup` affecting `line-height` in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* ========================================================================== * Embedded content * ========================================================================== */ /* * Remove border when inside `a` element in IE 8/9. */ img { border: 0; } /* * Correct overflow displayed oddly in IE 9. */ svg:not(:root) { overflow: hidden; } /* ========================================================================== * Figures * ========================================================================== */ /* * Address margin not present in IE 8/9 and Safari 5. */ figure { margin: 0; } /* ========================================================================== * Forms * ========================================================================== */ /* * Define consistent border, margin, and padding. */ fieldset { border: 1px solid silver; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } /* * 1. Correct `color` not being inherited in IE 8/9. * 2. Remove padding so people aren't caught out if they zero out fieldsets. */ legend { border: 0; /* 1 */ padding: 0; /* 2 */ } /* * 1. Correct font family not being inherited in all browsers. * 2. Correct font size not being inherited in all browsers. * 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome. */ button, input, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 2 */ margin: 0; /* 3 */ } /* * Address Firefox 4+ setting `line-height` on `input` using `!important` in * the UA stylesheet. */ button, input { line-height: normal; } /* * Address inconsistent `text-transform` inheritance for `button` and `select`. * All other form control elements do not inherit `text-transform` values. * Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+. * Correct `select` style inheritance in Firefox 4+ and Opera. */ button, select { text-transform: none; } /* * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` * and `video` controls. * 2. Correct inability to style clickable `input` types in iOS. * 3. Improve usability and consistency of cursor style between image-type * `input` and others. */ button, html input[type="button"], input[type="reset"], input[type="submit"] { -webkit-appearance: button; /* 2 */ cursor: pointer; /* 3 */ } /* * Re-set default cursor for disabled elements. */ button[disabled], html input[disabled] { cursor: default; } /* * 1. Address box sizing set to `content-box` in IE 8/9/10. * 2. Remove excess padding in IE 8/9/10. */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /* * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome. * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome * (include `-moz` to future-proof). */ input[type="search"] { -webkit-appearance: textfield; /* 1 */ -moz-box-sizing: content-box; -webkit-box-sizing: content-box; /* 2 */ box-sizing: content-box; } /* * Remove inner padding and search cancel button in Safari 5 and Chrome * on OS X. */ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /* * Remove inner padding and border in Firefox 4+. */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /* * 1. Remove default vertical scrollbar in IE 8/9. * 2. Improve readability and alignment in all browsers. */ textarea { overflow: auto; /* 1 */ vertical-align: top; /* 2 */ } /* ========================================================================== * Tables * ========================================================================== */ /* * Remove most spacing between table cells. */ table { border-collapse: collapse; border-spacing: 0; } /* ========================================================================== * CSS SETTING * by Hiroaki WAKATSUKI * Converted 2014/2/16 * ========================================================================== */ *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } img, object, embed { max-width: 100%; height: auto; } object, embed { height: 100%; } .left { float: left; } .right { float: right; } .clearfix { *zoom: 1; } .clearfix:after { content: "\0020"; display: block; height: 0; clear: both; overflow: hidden; visibility: hidden; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } .text-justify { text-align: justify; } .hide { display: none; } .antialiased { -webkit-font-smoothing: antialiased; } img { display: inline-block; vertical-align: middle; } textarea { height: auto; min-height: 50px; } select { width: 100%; } i { font-style: normal; } .animate { -moz-transition-property: all; -o-transition-property: all; -webkit-transition-property: all; transition-property: all; -moz-transition-duration: 0.2s; -o-transition-duration: 0.2s; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; -moz-transition-timing-function: ease-in; -o-transition-timing-function: ease-in; -webkit-transition-timing-function: ease-in; transition-timing-function: ease-in; } .button { background-image: -moz-linear-gradient(top, rgba(255, 255, 255, 0.05) 1%, rgba(0, 0, 0, 0.2) 100%); background-image: -webkit-linear-gradient(top, rgba(255, 255, 255, 0.05) 1%, rgba(0, 0, 0, 0.2) 100%); background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.05) 1%, rgba(0, 0, 0, 0.2) 100%); } ul { margin: 0; padding: 0; } ul li { list-style: none; padding: 0; margin: 0; } .row { width: 100%; margin-left: auto; margin-right: auto; margin-top: 0; margin-bottom: 0; max-width: 660px; *zoom: 1; } .row .grid-1, .row .grid-2, .row .grid-3, .row .grid-4, .row .grid-5, .row .grid-6, .row .grid-7, .row .grid-8, .row .grid-9, .row .grid-10, .row .grid-11, .row .grid-12 { float: left; margin-left: 0.9%; margin-right: 0.9%; } .row .grid-1 { width: 6.53333%; } .row .grid-2 { width: 14.86667%; } .row .grid-3 { width: 23.2%; } .row .grid-4 { width: 31.53333%; } .row .grid-5 { width: 39.86667%; } .row .grid-6 { width: 48.2%; } .row .grid-7 { width: 56.53333%; } .row .grid-8 { width: 64.86667%; } .row .grid-9 { width: 73.2%; } .row .grid-10 { width: 81.53333%; } .row .grid-11 { width: 89.86667%; } .row .grid-12 { width: 98.2%; } .row:before, .row:after { content: " "; display: table; } .row:after { clear: both; } .row.collapse > .column, .row.collapse > .columns { position: relative; padding-left: 0; padding-right: 0; float: left; } .row.collapse .row { margin-left: 0; margin-right: 0; } .row .row { width: auto; margin-left: -0.9375em; margin-right: -0.9375em; margin-top: 0; margin-bottom: 0; max-width: none; *zoom: 1; } .row .row:before, .row .row:after { content: " "; display: table; } .row .row:after { clear: both; } .row .row.collapse { width: auto; margin: 0; max-width: none; *zoom: 1; } .row .row.collapse:before, .row .row.collapse:after { content: " "; display: table; } .row .row.collapse:after { clear: both; } @media only screen and (max-width: 40em) { .row { width: 100%; padding: 0 20px !important; } .row .grid-1, .row .grid-2, .row .grid-3, .row .grid-4, .row .grid-5, .row .grid-6, .row .grid-7, .row .grid-8, .row .grid-9, .row .grid-10, .row .grid-11, .row .grid-12 { float: none; width: 100% !important; margin: 0 !important; position: static !important; } } /* max-width 640px, mobile-only styles, use when QAing mobile issues */ @media only screen and (min-width: 40.063em) and (max-width: 64em) { .row .grid-1, .row .grid-2, .row .grid-3, .row .grid-4 { width: 48.2% !important; } } /* min-width 641px and max-width 1024px, use when QAing tablet-only issues */
下図のように表示されていれば第2章は成功です。