【第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>
挙動としては下図のようになれば成功です。
削除前のトップページが下図
個別教科書の画面
削除ボタン押下後、トップページへ遷移すると該当の教科書が削除されている。
削除が正常にできていれば成功です。
お疲れ様でした!!!
基本的な機能は完了ですが、現在の実装の場合誰でも教科書の投稿や編集、削除ができてしまうため、
次章ではユーザー管理機能を説明する。