【本日の学習内容:resourcesを使ったCRUDアプリ】
resourcesを使ったCRUDアプリを実装しました。
git checkout -b add_resources(任意のブランチ名) コマンドを実行することで、add_resourcesブランチを作ったうえで切り替える。
✅resourcesの記述
Rails.application.routes.draw do
resources :users
end
✅アプリに書かれているルーティングを確認
rake routes コマンドを実行することで、アプリに書かれているルーティングを確認できる。
Prefix Verb URI Pattern Controller#Action
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
✅URLの部分を対応するPrefix_pathに書き換える
1️⃣index.html.erb
◀️書き換え前
<%= link_to "投稿画面へ", "/users/new" %>
▶️書き換え後
<%= link_to "投稿画面へ", new_users_path %>
◀️書き換え前
<%= link_to "編集", "/users/#{user.id}/edit", method: :get %>
▶️書き換え後
<%= link_to "編集", edit_user_path(user.id), method: :get %>
◀️書き換え前
<%= link_to "削除", "/users/#{user.id}", method: :delete, data: {confirm: "削除しますか?"} %>
▶️書き換え後
<%= link_to "削除", user_path(user.id), method: :delete, data: {confirm: "削除しますか?"} %>
2️⃣update.html.erb, destroy.html.erb, create.html.erb
◀️書き換え前
<%= link_to "一覧画面へ", "/users" %>
<%= form_with model: @user, url: users_path(@user.id), method: :post, local: true do |f| %>
▶️書き換え後
<%= form_with model: @user, url: users_path(@user.id), method: :post, local: true do |f| %>
3️⃣new.html.erb
◀️書き換え前
<%= form_with model: @user, url: "/users/#{@user.id}", method: :post, local: true do |f| %>
▶️書き換え後
<%= form_with model: @user, url: users_path(@user.id), method: :post, local: true do |f| %>
4️⃣edit.htnl.erb
◀️書き換え前
<%= form_with model: @user, url: "/users/#{@user.id}", method: :patch, local: true do |f| %>
▶️書き換え後
<%= form_with model: @user, url:user_path(@user.id), method: :patch, local: true do |f| %>
✅詳細情報の追加
1️⃣index.html.erbに以下を追記する。
<%= link_to "詳細", user_path(user.id), method: :get %>
2️⃣users_controllerに以下を追記する。
def show
@user = User.find(params[:id])
end
3️⃣showhtml.erbファイルの作成
ちなみに、method: :getと指定して記述しているところがあるが、記述しなかった場合はgetにいくので省略しても良い。
プルリクする(レビューをしてくださいという通知)
自分のPC内のソースコードをリモートリポジトリにプッシュし、他の人に変更内容を通知すること。
1️⃣git checkout -b add_resources(ここは任意のブランチ名) コマンドなどで新しいブランチを作成し、git add . コマンドとgit commit -m "メッセージ" コマンドを実行。
2️⃣リモートリポジトリを作る
4️⃣コミットした内容をリモートリポジトリにプッシュ
git push origin(リモートリポジトリのこと) add_resources コマンド でリモートリポジトリにプッシュする
GitHubでadd_resourcesというブランチが作成されたことを確認し、Compare&pull requestを押す。
どのブランチに対してプルリクエストを送るのかをしっかり確認してから、Create pull
requestボタンを押す。
5️⃣遷移したページ内で、先ほどプルリクしたブランチ名をクリックすると変更内容が確認できる。追加した内容は緑、削除した内容は赤で表示される。