【Rails】posts/show.html.erbでcomment#createしたい時のMissing Templateエラー

投稿詳細ページの下部に、その投稿へのコメント欄を作っていた時。
posts/show.html.erbからcomments#createを呼び出して、保存成功なら再度posts/show.html.erbredirect、保存失敗なら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


参考文献

よく忘れるRailsのコントローラーでのrenderメソッドのレシピ集 - Rails Webook