scaffoldを試してみた

はじめに
scaffoldについては、4年前のTECH:EXPERTでメンターの人が口にしていたのがきっかけで知った。
当時は使っていなかった。
そこにも、scaffoldについて書いてあった。
scaffoldとは
アプリの足場となる機能を提供してくれるもの。
データの登録、編集、削除、更新の処理の雛形を作ってくれる。
scaffoldをやってみる
【Rails】 Scaffolding機能の使い方を初心者向けにわかりやすく解説 | Pikawakaを参考にして、やっていこう。

日記機能を作成していく。

hiroki@shibatahiroshitakanoiMac money-app % rails generate scaffold dialy date:date title:string text:text
invoke active_record
create db/migrate/20240829124343_create_dialies.rb
create app/models/dialy.rb
invoke test_unit
create test/models/dialy_test.rb
create test/fixtures/dialies.yml
invoke resource_route
route resources :dialies
invoke scaffold_controller
create app/controllers/dialies_controller.rb
invoke erb
create app/views/dialies
create app/views/dialies/index.html.erb
create app/views/dialies/edit.html.erb
create app/views/dialies/show.html.erb
create app/views/dialies/new.html.erb
create app/views/dialies/_form.html.erb
create app/views/dialies/_dialy.html.erb
invoke resource_route
invoke test_unit
create test/controllers/dialies_controller_test.rb
create test/system/dialies_test.rb
invoke helper
create app/helpers/dialies_helper.rb
invoke test_unit
invoke jbuilder
create app/views/dialies/index.json.jbuilder
create app/views/dialies/show.json.jbuilder
create app/views/dialies/_dialy.json.jbuilder
pending migrationエラーを解決していく

こちらのエラーの原因は、マイグレーションファイルに書かれた内容がデータベースにマイグレーションされていないということ。

rails db:migrateを行うと、エラーが解消した。


新規投稿画面にアクセスしてみる
ルーティングには、resourcesが追加されていた。

今回、scaffoldで作成した日記機能に関するルーティングをrails routesにオプションをつけて確認してみよう。
rails routes コマンドの使い方を参考にする。

今回、新規作成されたコントローラのクラス名は、DialiesController。

そのDialiesControllerをオプションで指定する。
日記機能に関するルーティングが表示された。

試しに、新規投稿画面にアクセスしてみよう。
URI Patternは、/dialies/new。
rails sでローカルサーバーを起動させた後に、ルートのURLのlocalhost:3000にアクセスした。
そして、この相対パスを追加したアドレスにアクセスする。

日記の新規投稿画面にアクセスすることができた。
今日の日記を投稿してみる
早速、日記機能を試してみよう。
データを入れた後に、Create Dialyを押す。

詳細ページに飛んだ。サクセスメッセージと共に。

日記の一覧画面を表示してみる
データをもう一件追加したあとに、日記の一覧画面にアクセスしてみたい。

二つ目のデータが投稿された。

Back to dialiesを押してみる。
一覧ページが表示された。

日記の詳細ページを表示させる
show this dialyをクリックすると、日記の詳細ページに飛んだ。

日記の編集ページで日記を更新してみる
Edit this dialyをクリックすると、すでに投稿したデータを編集する画面に遷移した。

本文に追記して、Update Dialyをクリックする。

更新のサクセスメッセージが表示された。そして、本文が追記された。

Back to dialiesで一覧ページに戻ると、更新されたデータが表示されていた。

日記を削除してみる
詳細ページで、Destroy this dialyを押してみる。

削除のサクセスメッセージが表示された一覧ページに遷移した。ID : 2のデータは削除されていた。

コメントを残す