【Rails】posts/show.html.erbでcomment#createしたい時のMissing Templateエラー
投稿詳細ページの下部に、その投稿へのコメント欄を作っていた時。
posts/show.html.erb
からcomments#create
を呼び出して、保存成功なら再度posts/show.html.erb
にredirect
、保存失敗ならrender
をさせようとして結構ハマった。
次のように書くとrender
した時にMissing Template
エラーが出る。posts#show
を呼んでほしいのに、comments#show
を探しちゃってるっぽい。
# comments_controller.rb def create @post = Post.find(params[:post_id]) @comments = @post.comments @comment = Comment.new(comment_params) @comment.post_id = @post.id if @comment.save redirect_to post_path(@post.id) else render post_path(@post.id) end end
こんな時は明示的に「posts/show
のテンプレートを呼び出してくれ」と指定しましょう。render
部分を次のように書き換え。
render template: 'posts/show'
結構ハマったけどこれでようやく解決しました。
該当部分周辺のコード全文↓
# config/routes.rb resources :posts do resources :comments, only: [:create] end
<%# posts/show.html.erb %> <%= form_with model: @comment, url: post_comments_path(@post.id), method: :post, local: true do |f| %> <table> <tr> <td><%= f.text_field :comment, value: @comment.comment, placeholder: 'コメント' %></td> <td><%= f.submit '送信' %></td> </tr> </table> <% end %>
# posts_controller.rb def show @post = Post.find(params[:id]) @comment = Comment.new end
# comments_controller.rb def create @post = Post.find(params[:post_id]) @comments = @post.comments @comment = Comment.new(comment_params) @comment.post_id = @post.id if @comment.save redirect_to post_path(@post.id) else render template: 'posts/show' end end private def comment_params params.require(:comment).permit(:post_id, :comment) end