shimmyShow Webアプリ開発ブログ

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

【第6章】オンライン教科書サービス作成【教科書の削除機能】

目的

第5章によって教科書の編集ページを作成した教科書の編集ができるようになったため、本章で投稿したテキストの削除機能を実装する。

ルーティング設定

config/routes.rbを下記のように実装する。

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

コントローラーの実装

上記にてdestroyアクションのルーティングを設定したので、コントローラーにdestroyアクションを実装していく。
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

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

  def update
    text = Text.find(params[:id])
    text.update(text_params)
    redirect_to text_path(text.id)
  end

  def destroy
    text = Text.find(params[:id])
    text.destroy
    redirect_to root_path
  end

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

end

ビューファイルへ削除ボタンの追加

削除機能は各教科書ビューから実施できるよう各教科書のビューへ削除ボタンを用意する。
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="textManage">
  <%= link_to "テキスト編集", edit_text_path(@text.id), class: "textManage__edit" %>
  <%= link_to "テキスト削除", text_path(@text.id), method: :delete, class: "textManage__delete" %>
</div>
<div class="textText">
  <%= simple_format @text.body %>
</div>

挙動としては下図のようになれば成功です。
削除前のトップページが下図
f:id:erwinmarvin:20200917225039p:plain 個別教科書の画面 f:id:erwinmarvin:20200917225059p:plain 削除ボタン押下後、トップページへ遷移すると該当の教科書が削除されている。 f:id:erwinmarvin:20200917225118p:plain

削除が正常にできていれば成功です。
お疲れ様でした!!!

基本的な機能は完了ですが、現在の実装の場合誰でも教科書の投稿や編集、削除ができてしまうため、
次章ではユーザー管理機能を説明する。