Q&A
現状
現状は、ログインユーザーのプロフィールは表示されておりますが、ログインユーザー以外のユーザーの名前を押下すると、下記のようなエラーになります。
実現したいこと
一覧画面に表示されている各ユーザーの名前の押下時に、
そのユーザーのプロフィールが表示されるようにしたい。
どなたか分かられる方がおられましたら、ご教示のほどお願い致します。
発生している問題・エラーメッセージ
undefined method `profile' for nil:NilClass <tr> <th scope="row"><%= "profile" %></th> <td><%= @user.profile %></td> </tr> <tr> <th scope="row"><%= "hobby" %></th>
エラー箇所のビューファイル
app/views/users/show.html.erb
1<div class="container pt-3"> 2 <div class="row"> 3 <div class="col-md-10 offset-md-1"> 4 <h1 class="float-left mb-5"><%= "Profile" %></h1> 5 <table class="table"> 6 <tr> 7 <th scope="row"><%= "profile" %></th> 8 <td><%= @user.profile %></td> 9 </tr> 10 <tr> 11 <th scope="row"><%= "hobby" %></th> 12 <td><%= @user.hobby %></td> 13 </tr> 14 </table> 15 <%= render partial: "relationships/follow_button", locals: { user: @user } %> 16 </div> 17 </div> 18</div>
その他実装中コード
app/controllers/users_controller.rb
1class UsersController < ApplicationController 2 def new 3 @user = User.new 4 end 5 6 def create 7 @user = User.new(user_params) 8 if @user.save 9 auto_login(@user) 10 redirect_to events_path, success: 'ユーザー登録が完了しました' 11 else 12 flash.now[:danger] = 'ユーザー登録に失敗しました' 13 render :new 14 end 15 end 16 17 def show 18 @user = User.find_by(id: params[:id]) 19 end 20 21 private 22 23 def user_params 24 params.require(:user).permit(:email, :name, :password, :password_confirmation, :profile, :hobby) 25 end 26end
config/routes.rb
1 resources :users, only: %i[new create show]
app/views/events/show.html.erb
1<div class="d-flex align-items-center gap-3 mb-3"> 2 <%= link_to @event.user.name, user_path, class: 'nav-link' %> 3 4以下省略 5
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。