初心者なのでわからないことだらけです
前提・実現したいこと
ログインしている以外の人が編集ページに遷移できないようにしたい
ログインしている自分が自分の編集ページに直接入力するとエラーになってしまう
発生している問題・エラーメッセージ
NoMethodError in PrototypesController#edit
undefined method `user_id' for nil:NilClass
Extracted source (around line #54):
def move_to_index unless if user_signed_in? current_user.id == @prototype.user_id redirect_to action: :index end end
該当のソースコード
app/Controller/prototypesController
1 2class PrototypesController < ApplicationController 3 before_action :authenticate_user!, only: [:new,:edit,:destroy] 4 before_action :move_to_index, only: [:edit] 5 6 def index 7 @prototype = Prototype.all 8 end 9 10 def new 11 @prototype = Prototype.new 12 end 13 14 def create 15 @prototype = Prototype.new(prototype_params) 16 if @prototype.save 17 redirect_to root_path(@prototype) 18 else 19 render :new 20 @prototype = Prototype.includes(:user) 21 end 22 end 23 24 def show 25 @prototype = Prototype.find(params[:prototype_id] || params[:id]) 26 @comment = Comment.new 27 @comments = @prototype.comments.includes(:user) 28 end 29 30 def edit 31 @prototype = Prototype.find(params[:id]) 32 end 33 34 def update 35 @prototype = Prototype.find(params[:id]) 36 if @prototype.update(prototype_params) 37 redirect_to action: "show" 38 else 39 render :edit 40 end 41 end 42 43 def destroy 44 prototype = Prototype.find(params[:id]) 45 prototype.destroy 46 redirect_to action: "index" 47 end 48 49 private 50 def prototype_params 51 params.require(:prototype).permit(:title, :catch_copy, :concept, :image).merge(user_id: current_user.id) 52 end 53 54 def move_to_index 55 unless if user_signed_in? current_user.id == @prototype.user_id 56 redirect_to action: :index 57 end 58 end 59end
自分で調べたことや試したこと
一番最後のところ
def move_to_index unless if user_signed_in? current_user.id == @prototype.user_id redirect_to action: :index end end
上記の 『==』の中身を
『現在ログインしている人==あるプロトタイプを投稿した人』
の記述にするのが正解かと思ったがプログラミング用語にするとどう表記すればいいかわからない
インデントが消えちゃってて見づらいです。
コードを「```」で囲うといい感じになると思うので、質問文の編集をお願いします🙏
書き方例↓
```rb
class PrototypesController < ApplicationController
...
end
```
ログイン機能を作るために、何か gem を使っていますか?
使っている場合は、その gem の名前も質問文に追記してもらえると助かります。
shinoharat様
この度は質問いただきありがとうございます。
とてもご親切に対応いただき、大変ありがたいです。
本件ですが、自己解決いたしました。
いただいたアドバイスですが次から活用させていただきます。
今回使っているgemはdeviseでして
インデントも知らなかったので活用していきたいと思います。
何かありましたらまたご指導の程、よろしくお願いいたします。
今回は本当にありがとうございました。
回答1件
あなたの回答
tips
プレビュー