ログイン機能を持ったCURDアプリを作っています
ログイン機能はDeviseを使いました
そこで問題が生じています
Diveseで登録したユーザーの詳細画面(user/show.html)に非ログイン時にアクセスした場合画像のようなエラーが出ます
詳細ページのユーザーIDとログインしているIDが一致すれば編集可能
一致しなければ閲覧のみ
という仕様にしています
コードは下記です
足りないファイル/コード等があるときは修正するのでお申し付けください
ログインしていないので@userも何もないからエラーになっていると思っていますがその解決策がわかりません
Userコントローラー
Ruby
1class UsersController < ApplicationController 2 def index 3 @users = User.all 4 end 5 6 def show 7 @user = User.find(params[:id]) 8 9 end 10 11 def update 12 @user = User.find(params[:id]) 13 @user.update(user_params) 14 redirect_to user_path(@user) 15 end 16 17 def edit 18 @user = User.find(params[:id]) 19 end 20 21 private 22 def user_params 23 params.require(:user).permit(:username, :email, :profile, :profile_image) 24 end 25end 26
user/show.html.erb
HTML
1<div class='row'> 2 <div class='userShow col-sm-9 offset-2'> 3 <div class='content-imgCenter'> 4 <%= attachment_image_tag @user, :profile_image, fallback: 'no-image.png' %> 5 </div> 6 <table> 7 <tr> 8 <td class='nowrapTd'>ユーザー名</td> 9 <td class='nowrapTd'><%= @user.username %></td> 10 </tr> 11 <tr> 12 <% if @user.id == current_user.id %> 13 <td class='nowrapTd'>メールアドレス</td> 14 <td class='nowrapTd'><%= @user.email %></td> 15 <% end %> 16 </tr> 17 <tr> 18 <td class='nowrapTd'>自己紹介</td> 19 <td><%= @user.profile %></td> 20 </tr> 21 <tr> 22 <% if @user.id == current_user.id %> 23 <td><%= link_to '編集', edit_user_path(@user), class: 'btn btn-success' %></td> 24 <td></td> 25 <% end %> 26 </tr> 27 </table> 28 29 </div> 30</div> 31 32<div class='row'> 33 <div class='col-sm-9 offset-2'> 34 <h2>投稿一覧</h2> 35 <div class='card row'> 36 <% @user.contents.each do |content| %> 37 <div class='userCard col-sm-4'> 38 <div class='content-imgCenter'> 39 <%= link_to content_path(content) do %> 40 <%= attachment_image_tag content, :image, fallback: 'no-image.png' %> 41 <% end %> 42 </div> 43 <div class='content_title'> 44 <%= link_to content_path(content) do %> 45 <h3><%= content.title %></h3> 46 <% end %> 47 </div> 48 <div class='time'> 49 <%= content.updated_at.strftime("%Y-%m-%d %H:%M") %> 50 </div> 51 </div> 52 <% end %> 53 </div> 54 </div> 55</div>
非ログイン時でも閲覧のみは可能にしたいのですがどうすればいいのでしょうか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。