独学でポートフォリオのSNSアプリを開発しています。
posts/show 内で投稿へのコメント機能を実装していたのですが、コメントフォームが空欄の状態で、Commentsコントローラーのcreateアクションを実行すると、(図1)のようなエラーが発生しました。
(図2)の13行目を参照すると、Commentsコントローラー内から, Postsコントローラーのshowアクションをレンダリングする際に、postのkey(ID)が渡されていないことが原因だと考えました。
同じコントローラー内であれば、railsがshowアクションに渡すkeyを自動的に解釈すると理解しているのですが、コントローラーが異なる場合、どのようにコードすれば正しくレンダリングされるのでしょうか。
また、突貫工事として(図3)のようなリダイレクトではエラーを回避しました。
(図2)
class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = current_user.comments.new(comment_params) if @comment.save redirect_to request.referer, notice: "コメントを投稿しました。" else flash.now.alert = 'コメントの作成に失敗しました。' render template: "posts/show", status: :unprocessable_entity end end def edit @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) if @comment.update(comment_params) redirect_to post_path(@post), notice: "コメントを編集しました。" else flash.now.alert = "コメントの編集に失敗しました。" render :edit, status: :unprocessable_entity end end def destroy @comment = Comment.find(params[:id]) @comment.destroy redirect_to request.referer, notice: "コメントを削除しました。", status: :see_other end private def comment_params params.require(:comment).permit(:context, :reply_comment_id).merge(post_id: params[:post_id]) end end
(図3)※変更したcreateアクション内のみ記述。
class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = current_user.comments.new(comment_params) if @comment.save redirect_to request.referer, notice: "コメントを投稿しました。" else redirect_to request.referer, notice: "コメントの作成に失敗しました。", status: :see_other end end
質問経験が浅く拙い文章ですが、ご教授いただけますと幸いです。
回答1件
あなたの回答
tips
プレビュー