2020-12-11に投稿

2020.12.11 * chapter機能

本日のゴール

■ chapterごとに登録・削除できるようにする
image

chapterテーブルの初期値を投入

Index and Edit and Delete画面を作りたいと思います。
今までwordsテーブルのchapter_idはnullのままにしていたので、まずここを登録できるようにします。

chapterテーブルはとりあえず初期データを登録しておくことにするので、seed.rbを使います。
db/seed.rb

# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
#   movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
#   Character.create(name: 'Luke', movie: movies.first)
for i in 1..5 do
    Chapter.create(name: "chapter#{i}")
end

chapter1~chapter5を登録するスクリプトです。
コマンドでデータを投入します。
$ rails db:seed
sqliteでテーブルを確認すると
image.png
ちゃんと投入できていました!

chapter一覧画面作成

まずChapterコントローラを作成して、indexで一覧表示させます。
$ rails g controller Chapters
chapters_controller.rb

class ChaptersController < ApplicationController
    def index
        @chapters = Chapter.all
    end
end

views/chapters/index.html.erb

<% @chapters.each do |chapter| %>
    <div>
        <%= chapter.name %>
    </div>
<% end %>

単語をchapterごとに表示させる

先ほど作成したviews/chapters/index.html.erbにwords一覧画面へのリンクを付けます。
リンクが呼ぶのはwordsコントローラのindexアクションです。パラメータとしてchapter_idを渡します。

<% @chapters.each do |chapter| %>
    <div>
        <%= chapter.name %>
        <%= link_to 'Show Words', words_path(chapter_id: chapter.id) %>
    </div>
<% end %>

localhost:3000/chaptersはこうなりました
image.png

indexアクションは今までwordsを全件抽出していましたが、これをchapter_idで絞り込むようにします。
words_controller.rb

class WordsController < ApplicationController
  def index
    @words = Word.where(chapter_id: params[:chapter_id])
  end

DBにレコードを登録しておいて(chapter_id=1が3件、chapter_id=2が2件にしました)
localhost:3000/chaptersからリンクを踏んでみます。
image.png
URLはhttp://localhost:3000/words?chapter_id=1となっていました。
ここをTOP画面にしたいので、routes.rbを修正します。

Rails.application.routes.draw do
  root 'chapters#index'

index, create, deleteをまとめる

chapterを選択した後の画面でwordsの一覧表示、追加、削除を行えるようにします。
words/index.html.erb

<h1>WORDS - CHAPTER<%= @chapter_id %></h1>
<div>
<% @words.each do |word| %>
    <div>
        ID: <%= word.id %> |
        ENGLISH: <%= word.english %> |
        JAPANESE: <%= word.japanese %>
        <%= button_to 'Delete', word_path(word), method: :delete %>
        ----------
    </div>
<% end %>
<p>*ADD NEW WORDS*</p>
<%= render 'form' %>
</div>

以前作成していたフォームを追加して、editを削除しました。
_form.html.erb

<%= form_with model: @new, local:true do |f| %>
    <div>
        <%= f.label :english %>
        <%= f.text_field :english %>
    </div>
    <div>
        <%= f.label :japanese %>
        <%= f.text_field :japanese %>
    </div>
    <%= f.hidden_field :chapter_id, :value => @chapter_id %>
    <%= f.submit %>
<% end %>

model: @word だった部分を@newとし(words/index.html.erbにはもともと@wordsを渡しているのでややこしいから変更)、hidden_fieldを使ってchapter_idが勝手に登録されるようにしています。
words_controllerも修正

class WordsController < ApplicationController
  def index
    @chapter_id = params[:chapter_id]
    @words = Word.where(chapter_id: params[:chapter_id])
    @new = Word.new
  end
   〜中略〜
  def create
    @word = Word.new(word_params)
    @word.save
    redirect_to words_path(word_params)
  end

indexアクションにはフォームで使用する@newを追加、
createアクションにはredirect_toの引数を追加しました。word_paramsは[:chapter_id]を引数として受け取るように定義してあるので、これによってチャプターの単語一覧画面にリダイレクトされます。
image.png
こんな感じになりました

宿題

ルーティングやアクションをいろいろ変更したので、リダイレクト先がおかしかったり使わないviewsが出てきたりしてしまいました。
整理したい!!

おわり*0 v 0

ツイッターでシェア
みんなに共有、忘れないようにメモ

view_list Ruby on Railsを使ったwebアプリ開発の記録
第5回 2020.11.12 * 単語の一覧表示
第6回 2020.11.16 * 編集機能
第7回 2020.11.17 * 画面設計
第8回 2020.12.11 * chapter機能
第9回 2020.12.31 * テスト機能作成

same.__.same

Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。

また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!

有料記事を販売できるようになりました!

こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?

コメント