Q&A
前提
railsにてフォロー機能を作成しており、先日レビューを出したところ、
relationships.find_by(followed_id: user_id).destroy の部分にて、
「relationships.find_by(followed_id: user_id)でデータが見つからなかった際に、
その後にあるdestroyメソッドを実行するとエラーになるため、エラーにならないように対策した方がいい」と指摘がありました。
[フォロー機能参考資料]:https://qiita.com/nakachan1994/items/e6107fe3003f6515e385
実現したいこと
- relationships.find_by(followed_id: user_id).destroy以外の他の記述方法が知りたい。
発生している問題・エラーメッセージ
エラー等は特に発生しておりません。
該当のソースコード
app/models/user.rb
1 # フォローしたときの処理 2 def follow(user_id) 3 relationships.create(followed_id: user_id) 4 end 5 # フォローを外すときの処理 6 def unfollow(user_id) 7 relationships.find_by(followed_id: user_id).destroy ←ここの箇所で指摘が入りました。 8 end 9 # フォローしているか判定 10 def following?(user) 11 followings.include?(user) 12 end
app/controllers/relationships_controller.rb
1class RelationshipsController < ApplicationController 2 def create 3 current_user.follow(params[:user_id]) 4 redirect_to request.referer 5 end 6 7 def destroy 8 current_user.unfollow(params[:user_id]) 9 redirect_to request.referer 10 end 11end
試したこと
https://qiita.com/nakayuu07/items/3d5e2f8784b6f18186f2
https://www.sejuku.net/blog/13000
上記以外にも色々と調べてみましたが、
知識が乏しく解決策が見つけられない状態でございます。
どなたか別の記述方法が分かられる方がいらっしゃいましたら、
ご教示のほどお願い致します。
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2023/01/26 02:54
2023/01/26 03:21
2023/01/26 03:24