shimmyShow Webアプリ開発ブログ

プログラミングスクールTECH::CAMPを73期を卒業し、紙媒体で実施されている教育の根本を変えていくためのサービスを開発中。当ブログを読めば誰でも当該サービスを開発できるようにするため軌跡を記録中。

【第4章】オンライン教科書サービス作成【個別教科書の表示】

目的

第3章では教科書の投稿機能を実装した。本章では投稿した教科書の表示機能を実装し、個別の教科書を表示できるようにする。

ルーティング設定

showアクションへのルーティングを設定する。 config/routes.rbを下記のように実装する。

Rails.application.routes.draw do
  root to: 'texts#index'
  resources :texts, only: [:new, :create, :show]
end

コントローラーの実装

上記にてshowアクションのルーティングを設定したので、コントローラーにshowアクションを実装していく。
app/controllers/texts_controller.rbを下記のように実装する。

class TextsController < ApplicationController

  def index
    @texts = Text.all
  end

  def new
    @text = Text.new
  end

  def create
    Text.create(text_params)
    redirect_to root_path
  end

  def show
    @text = Text.find(params[:id])
  end

  private
  def text_params
    params.require(:text).permit(:title, :abstract, :body).merge(public_flag: "1")
  end

end

ビューファイル作成

showアクションをコントローラーに実装したので、対応するビューファイルを作成する。
app/views/texts/show.html.erb

<div class="textTitle">
  <%= @text.title %>
</div>
<div class="textDate">
  <%= @text.created_at %>
</div>
<div class="textAuthor">
</div>
<div class="textText">
  <%= simple_format @text.body %>
</div>

トップページから各教科書のページへ遷移できるようにリンクを実装する。
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">
        <%= link_to text.title, text_path(text.id), class: "content__right__top--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 %>

下図のように表示されれば成功です。
f:id:erwinmarvin:20200917221333p:plain

教科書の表示機能の基本的な部分は完了です。
次の章で投稿した教科書の編集や削除機能を説明いたします。