1
0

More than 1 year has passed since last update.

ユーザー詳細ページで params[:id] が取得できない

Last updated at Posted at 2022-03-07

自作でグループ内で共有できるカレンダーアプリの作成中。

【やりたい事】
①ユーザー登録
②マイページに遷移(root_path)
③参加中のグループを表示
④グループ名をクリックすると、該当グループのカレンダーへ遷移

ユーザー登録は無事に完了。
本日はマイページの作成に取り掛かる。

以下各コード。

user_controller
class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
  end
end
show.html.erb
<div class="mypage">
  <div class="left-contents">
    <div class="image">
    <%= image_tag @user.image.variant(resize: '300x300'), class: 'profile-image' if current_user.image.attached? %>
    </div>
    <% if user_signed_in? && current_user %>
    <%= link_to "マイページ編集",edit_user_path(:id), class: "compilation" %>
    <% end %>
  </div>
  <div class="right-contents">
    <div class="user-name2">
      <p><%= @user.name %>のマイページ</p>
    </div>
    <div class="user-department">
      <p>部署名:<%= @user.department_name %></p>
    </div>
    <div class="group_name">
      <p>参加中のグループ</p>
    </div>
  </div>
</div>

上記2箇所を記述し、いざrails sを実行。

が、エラー発生

エラー文
Couldn't find User without an ID

意味は「IDが見つからない」とのこと。

記述でもミスったかな?

まずはSequel ProでDBを確認。

???

ちゃんと保存されている。
意味がわからない・・・

show.html.erb@usercurrent_userに変更してみる。
すると問題なく、ページが表示。
ページ内のユーザー名、部署名、画像もきちんと表示されている。
ますます意味がわからない・・・

2時間以上調べて、一つの記事を発見。
root_pathは普通、直接アクセスしてくるものなので任意のパラメータを付け加えるのが難しい

これか!
たしかに今回、showアクションをroot_pathに設定している。
過去にオンライン学習で作ったアプリのコードを見ても確かにroot_pathを設定したページにパラメーターの記述がない。

各ユーザーのマイページを表示させたいので、 @user = User.find(params[:id])は変えたくない。
となるとroot_pathを他のページに設定するしかない。

う〜ん、カレンダーをトップページに持ってくるか。
また設計の練り直し・・・

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0